Jquery UI动态创建按钮未触发事件

时间:2013-09-23 05:04:05

标签: jquery-ui jquery-ui-dialog jquery

我使用Jquery UI创建了两个按钮,并将以下事件附加到其中。

function testconfirm() {
   alert( "testconfirm");
} 

function testCancel() {
   alert( "testCancel");
}

仅在第一次未触发事件时。之后它的工作正常。

http://jsfiddle.net/qNGEw/26/

任何人都可以帮我确定以下小提琴中发布的代码有什么问题吗?

1 个答案:

答案 0 :(得分:1)

它总是会触发点击事件,但你这样做可能不是你想要的那样。 首先,您将事件绑定到按钮作为测试功能。因此,首先单击执行测试函数作为其处理程序,您再次解除绑定并绑定警告消息的实际处理程序。因此,最终从您的第二次点击开始,它执行了具有警报的处理程序。

 function test() {
            //Binding during the first click
            $('#btnconfirm').unbind('click').on("click", testconfirm);
            $('#btnCancel').unbind('click').on("click", testCancel);
        }
        var buttonPane = $("#message1");
        $.each(dialog_buttons, function (index, props) {
            $(buttonPane).append('<span class="ui-button-text" id="btn' + props.id + '">' + props.text + '</span>');
              //Binding for the first time
            $('#btn' + props.id).button().unbind('click').on("click", test); 

        });

您可以通过以下方式轻松解决此绑定问题:

当您为对话框按钮设置道具时,也要为处理程序添加属性。

var AlertTest = {
    "message1": {
        "buttons": [{
            id: "confirm",
            text: "Yes",
            handler: testconfirm //add one more property for the handler
        }, {
            id: "Cancel",
            text: "No",
            handler: testCancel //add one more property for the handler
        }]

    }
}

并在创建按钮时绑定事件。

 $('#btn' + props.id).button().on("click", props.handler);

<强> Fiddle

相关问题