1

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')));

        };

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.

How could I manage $("#nestable .button-delete").on("click", deleteFromMenu); to see only one confirm question. Thanks.

4

2 回答 2

1

您可以使用removeEventListeneroff()删除之前的事件侦听器。

$("#nestable .button-delete").off().on("click", deleteFromMenu);
$("#nestable .button-edit").off().on("click", deleteFromMenu);

更新(给出更好的解决方案)

如果#nestable是静态的,您应该将侦听器事件移到addToMenu方法之外。

格式:$(staticAncestors).on(eventName, dynamicChild, function() {});

所以在你的情况下

// set events
  $("#nestable").on("click", '.button-delete', deleteFromMenu);
  $("#nestable").on("click", '.button-edit', prepareEdit);

var addToMenu = function () {
  ....
  // update JSON
  updateOutput($('#nestable').data('output', $('#json-output')));
};

阅读以下帖子以更好地理解。

动态创建元素的事件绑定?

于 2020-02-25T03:23:33.473 回答
1

使用.off(). 该.off()方法删除了附加的事件处理程序.on()

所以在你的情况下:

 $("#nestable .button-delete").off().on("click", deleteFromMenu);
于 2020-02-25T03:16:15.733 回答