-1

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

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

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

只有第一次没有触发事件。之后它的工作正常。

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

谁能帮我确定以下小提琴中发布的代码有什么问题?

4

1 回答 1

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);

小提琴

于 2013-09-23T05:12:11.687 回答