我在 jQuery 对话框中的删除按钮上遇到了一个奇怪的问题。应该发生的是,一旦单击删除按钮,它就会查找隐藏输入按钮的值并将该值发送到 ajax 调用以删除内容。因此,每次点击都应该只显示属于最后点击的按钮的单个 ID。
第一次单击它时实际发生了什么,它显示了正确的值。但是当你点击下一步按钮时,它会先显示以前的id,然后显示新的id,所以ajax调用会进行两次。如果您单击第三个按钮,它将显示三个 id,并进行三个 ajax 调用,这是不应该发生的。每次点击时它都应该坚持一次 ajax 调用,并且只显示最新的 id。
您可以在此处查看示例 http://jsfiddle.net/uF5fX/11/ ,其 id 显示在控制台中。 关于我做错了什么以及如何解决这个问题有什么想法吗?
$("#item-list").on( "click", ".delete-item", function( e ) {
var dialogBox = $("#delete-confirmation"),
storeId = $(this).next('input[name="store_id"]').val();
console.log( 'main clicked store id = ' + storeId );
dialogBox.dialog({
width: 325,
resizable : false,
modal: true,
minHeight: 0
});
$(".ui-dialog-titlebar").remove();
dialogBox.find(".button-secondary").on( "click", function() {
dialogBox.dialog("close");
});
dialogBox.find(".button-primary").on( "click", function( elem ) {
console.log( 'click delete btn' );
console.log( 'ajax store id = ' + storeId );
dialogBox.dialog("close");
//make a singe ajax call with the last storeId
//elem.stopImmediatePropagation();
elem.stopPropagation();
elem.preventDefault();
return false;
});
e.stopPropagation();
e.preventDefault();
return false;
});
html的结构
<ul id="item-list">
<li>
<input type="button" value="Delete" name="text" class="delete-item" />
<input type="hidden" value="60" name="store_id" />
</li>
</ul>
通常,当触发多次点击时,可以通过 return false 或 PreventDefault/stopPropagation 来修复,但这里没有区别吗?
最佳答案
每次单击“删除项目”时,对话框按钮都会绑定(bind)另一个新事件。
dialogBox.dialog({
width: 325,
resizable : false,
modal: true,
minHeight: 0
});
$(".ui-dialog-titlebar").remove();
var btn1 = dialogBox.find(".button-secondary");
var btn2 = dialogBox.find(".button-primary");
btn1.on( "click", function() {
dialogBox.dialog("close");
btn1.unbind('click');
btn2.unbind('click');
});
btn2.on( "click", function( elem ) {
console.log( 'click delete btn' );
console.log( 'ajax store id = ' + storeId );
dialogBox.dialog("close");
//make a singe ajax call with the last storeId
//elem.stopImmediatePropagation();
elem.stopPropagation();
elem.preventDefault();
btn1.unbind('click');
btn2.unbind('click');
return false;
});
关于javascript - 点击 jQuery UI 对话框多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20583639/