我正在创建简单的 jQuery 插件,可用于附加任何操作的确认。但面临非常奇怪的问题,它对于单个元素单击工作正常,但是当我要单击也与我的插件绑定(bind)的第二个元素时,它工作正常,但它也会触发先前单击的元素。
(function ($) {
$.fn.BootConfirm = function (options) {
// Establish our default settings
var settings = $.extend({
message: 'Are you sure about this ?',
complete: null
}, options);
var self = this;
var cointainer = '\
<div class="modal fade" id="confirmBoot" role="dialog" aria-labelledby="confirmDeleteLabel" aria-hidden="true">\
<div class="modal-dialog">\
<div class="modal-content">\
<div class="modal-header">\
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>\
<h4 class="modal-title">Confirm action</h4>\
</div>\
<div class="modal-body">\
<p>Are you sure about this ?</p>\
</div>\
<div class="modal-footer">\
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>\
<button type="button" class="btn btn-success btn-ok" id="confirm">Ok</button>\
</div>\
</div>\
</div>\
</div>';
return this.each(function () {
var self = this;
$(this).click(function () {
if (!$('#confirmBoot').length) {
$('body').append(cointainer);
}
if (settings.message) {
$('#confirmBoot').find('.modal-body').text($(this).attr('data-confirm'));
}
$('#confirmBoot').modal({ show: true });
if ($.isFunction(settings.complete)) {
$('#confirmBoot').find('.btn-ok').click(function () {
$.when(settings.complete.call(this, self)).done(function () {
$('#confirmBoot').modal("hide"); // Alerts "123"
});
});
}
});
});
}
}(jQuery));
这是我的回调函数:
function kaushik(myObject) {
ManageAcriveProducts(myObject);
};
我通过以下方式调用它
$('a[data-confirm]').BootConfirm({
complete: kaushik
});
有关更多详细信息,请检查此 js fidder Jsfiddle 。任何人都可以分享可能的解决方案或更好的方法来做到这一点。或者有没有更好的方法来实现这一目标?
最佳答案
问题是您在 bootconfirmed 对象上的每个点击事件上分配了对 btn-ok
的点击。每次点击都会链接到已点击的对象,因此每次点击 btn-ok
时,它都会出现在回调中。
一个简单的修复方法(尽管我不确定这是否是最好的)是在操作完成后删除对 btn-ok 的点击。像这样:
$.when(settings.complete.call(this, self)).done(function () {
$('#confirmBoot').modal("hide");
$('#confirmBoot').find('.btn-ok').off('click');
});
工作 fiddle :http://jsfiddle.net/ywunutyw/
编辑:
对以前的解决方案进行了一些改进,它可能需要一些调整,因为我没有研究细节,但它应该给你一些想法。为了防止添加 click
事件并在用户每次单击按钮时删除它们,您可以在每个按钮的 click
行为之外定义模态窗口上的 click
事件/非事件按钮。单击事件/非事件您可以定义将在模式确认中使用的目标。像这样:
在使用 this.each 调用行为之前:
$(document).on('click', '#confirmBoot .btn-ok',
function (e) {
if ($.isFunction(settings.complete)) {
console.log(self)
$.when(settings.complete.call(this, click_origin)).done(function () {
$('#confirmBoot').modal("hide");
});
}
});
然后在您事件/非事件的点击事件上:
click_origin = e.target;
参见 fiddle :http://jsfiddle.net/ywunutyw/1/
关于javascript - 为什么我的插件会触发多次回调或点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30607604/