我已经使用Jquery UI创建了两个按钮并将以下事件附加到它。Jquery UI动态创建按钮未触发事件
function testconfirm() {
alert("testconfirm");
}
function testCancel() {
alert("testCancel");
}
只有第一次事件没有被解雇。之后,它的工作很好。
谁能帮我识别的代码贴在下面的小提琴有什么不对?
我已经使用Jquery UI创建了两个按钮并将以下事件附加到它。Jquery UI动态创建按钮未触发事件
function testconfirm() {
alert("testconfirm");
}
function testCancel() {
alert("testCancel");
}
只有第一次事件没有被解雇。之后,它的工作很好。
谁能帮我识别的代码贴在下面的小提琴有什么不对?
它总是触发点击事件,但是你这样做可能不是你想要的方式。 首先你将事件绑定到两个按钮上作为测试函数。因此,首先单击执行测试函数作为其处理程序,您再次解除并绑定提醒消息的实际处理程序。因此,最终从第二次点击开始,它执行具有警报的处理程序。
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);
好的。那么我该如何从第一次触发事件呢?我需要针对按钮btncancel的按钮btnconfirm和testcancel调用testconfirm。我尝试像这样$('#btn'+ props.id).button()。unbind('click')。on(“click”,'#test'+ props.id);但它不起作用。 –
@ user833985看到我用小提琴更新的答案。你不需要太多补充。 – PSL
你为什么要绑定和解除绑定click事件和它不第一个点击工作的原因是因为你实际上是和解封的功能复位click事件'test'而不是触发它们 –
@Pascalz,当你第一次点击是按钮时它工作吗? –
@PatrickEvans,它的原因,否则我会得到两个警报的第二次点击和三个警报的第三次点击等等..所以每次我删除事件并再次绑定它。我不知道这是否是实际的解决方案。 –