我有一个文本框,可以在其中使用select2.js添加和删除项。现在我有一个要求,当我从文本框中删除项目时,它应该要求一些确认消息。
为此,我需要修改select2.js的select2.js方法。下面是我修改过的代码。
unselect: function (b) {
var $curelm = this;
var d = "", e= "", c = "";
confirmpopup("Confirm", "Are you sure you want to remove this Tag?", function (confirm) { // <-- Here i have added confirmpopup code
if (confirm) {
c = $curelm.getVal();
if (b = b.closest(".select2-search-choice"), 0 === b.length) throw "Invalid argument: " + b + ". Must be .select2-search-choice";
if (d = b.data("select2-data")) {
var f = a.Event("select2-removing");
if (f.val = $curelm.id(d), f.choice = d, $curelm.opts.element.trigger(f), f.isDefaultPrevented()) return !1;
for (;
(e = p($curelm.id(d), c)) >= 0;) c.splice(e, 1), $curelm.setVal(c), $curelm.select && $curelm.postprocessResults();
return b.remove(), $curelm.opts.element.trigger({
type: "select2-removed",
val: $curelm.id(d),
choice: d
}), $curelm.triggerChange({
removed: d
}), !0
}
}
});
},我准备了一个JS Fiddle给你看我的问题。
当我单击框中的"x"(移除符号)时,它将打开一个确认弹出,如果我单击"Yes"按钮,它将完美地从框中删除项目,而当我单击"No"按钮时,它将不会删除项目。到现在为止一切都很好。现在出现了问题,当我第二次单击框中的"x"并单击"Yes"按钮时,它将从框中删除2项,而不是仅删除选定的项。我不知道为什么,但它将维护以前的单击项历史记录(,我猜是)。
有谁能指出我在上述代码中做错了什么?
要在JS 中生成问题,请执行以下步骤:
"x"按钮,并在确认弹出中单击"No"按钮。"x"按钮,然后单击确认弹出上的"Yes"按钮。注意:我在JS中添加了整个代码,而不是将其添加到外部链接中,因为我已经更改了它的
unselect方法。
发布于 2016-03-22 10:43:14
好吧,在我的代码中做了一些深入研究之后,我得到了解决方案。confirmpopup()函数中的问题。当我单击项目从select2框中删除时,我已经注册了"Yes"按钮的单击事件。然后,我再次单击另一项从select2框中删除,再次单击"Yes"和"No"按钮事件,在DOM中注册确认弹出。这就是为什么"Yes"按钮点击2次事件的原因。
因此,为了克服这个问题,我必须首先使用代码中的方法解除绑定单击事件,如下所示。
function confirmpopup(title, message, callbackfunc) {
$('#errorlabel').text(title);
$('#popupmessage').text(message);
$('#modelconfirm').show();
$('#btnyes').off('click'); // <-- Solution is here
$('#btnyes').on('click', function () {
$('#modelconfirm').hide();
callbackfunc();
});
$('#btnno, .close').on('click', function () {
$('#modelconfirm').hide();
});
}https://stackoverflow.com/questions/36136129
复制相似问题