动态提供onclick,避免重复事件调用 [英] Provide onclick dynamically and avoid duplicate event calling
问题描述
我尝试添加一个项目,就像这个示例:https://codepen.io/Gobi_Ilai/pen/LLQdqJ
I try to add an item, just like this sample: https://codepen.io/Gobi_Ilai/pen/LLQdqJ
var addToMenu = function () {
var newName = $("#addInputName").val();
var newSlug = $("#addInputSlug").val();
var newId = 'new-' + newIdCount;
nestableList.append(
'<li class="dd-item" ' +
'data-id="' + newId + '" ' +
'data-name="' + newName + '" ' +
'data-slug="' + newSlug + '" ' +
'data-new="1" ' +
'data-deleted="0">' +
'<div class="dd-handle">' + newName + '</div> ' +
'<span class="button-delete btn btn-danger btn-xs pull-right" ' +
'data-owner-id="' + newId + '"> ' +
'<i class="fa fa-times" aria-hidden="true"></i> ' +
'</span>' +
'<span class="button-edit btn btn-success btn-xs pull-right" ' +
'data-owner-id="' + newId + '">' +
'<i class="fa fa-pencil" aria-hidden="true"></i>' +
'</span>' +
'</li>'
);
newIdCount++;
// update JSON
updateOutput($('#nestable').data('output', $('#json-output')));
// set events
$("#nestable .button-delete").on("click", deleteFromMenu);
$("#nestable .button-edit").on("click", prepareEdit);
};
var deleteFromMenu = function () {
var targetId = $(this).data('owner-id');
var target = $('[data-id="' + targetId + '"]');
var textConfirm = "Are you sure to delete" + target.data('name') + " ?";
var result = confirm(textConfirm);
if (!result) {
return;
}
// Remove children (if any)
target.find("li").each(function () {
deleteFromMenuHelper($(this));
});
// Remove parent
deleteFromMenuHelper(target);
// update JSON
updateOutput($('#nestable').data('output', $('#json-output')));
};
然后尝试删除其中一条记录.页面要求确认问题(1+添加记录)次.例如,如果尝试添加 2 条记录,并尝试删除一项(不是最后添加的项目),则会出现 3 条确认消息.
And after that try to delete one of the records. The page asked to confirm the question (1+added record) times. For example, if try to add 2 records, and try to delete one item(not last added item), 3 confirm message appears.
我如何管理 $("#nestable .button-delete").on("click", deleteFromMenu);
只看到一个确认问题.谢谢.
How could I manage $("#nestable .button-delete").on("click", deleteFromMenu);
to see only one confirm question.
Thanks.
推荐答案
使用 .off()
..off()
方法删除通过 .on()
附加的事件处理程序.
Use .off()
. The .off()
method removes event handlers that were attached with .on()
.
所以在你的情况下:
$("#nestable .button-delete").off().on("click", deleteFromMenu);
这篇关于动态提供onclick,避免重复事件调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!