0

我有一个包含许多按钮的页面,其中许多是我在初始 jQuery 加载后使用 ajax 添加的。

我的script.js文件中有一些处理程序,这是一个:

$('.editor-button.remove').click(function () {
 var row = $(this).parent('.row');
 row.remove();
});

我怎样才能确定:

  1. 处理程序总是附加到所有满足 jQuery 选择器的按钮,即使是那些刚刚通过 ajax 加载到页面的按钮
  2. 处理程序不会在每个 ajax 调用中将无数次附加到每个元素
  3. 使我的整个网站通过 jQuery 类而不是内联onclick处理程序处理的一般约定是什么,这是一个坏习惯吗?前两个问题显然也适用于这个问题。

我对通过 jQuery 概念进行事件处理非常陌生,我希望尽可能保持script.js干净,不要用本地化的东西污染它,另一方面,我希望我的按钮只包含类名,而不是加密函数等。一般规则是我的代码应该尽可能干净,而每个处理程序不会在每个 ajax 调用中附加无数次。
我不是在寻找我上面提到的问题的解决方案,而是寻找关于如何尽可能高效和清洁地处理 jQuery 处理程序的一般指南。

4

1 回答 1

5

Event delegation is what you're after:

$('#parent').on('click', '.editor-button.remove', function() {
    $(this).closest('.row').remove();
});

Make sure that #parent is present when the event handler is attached. If there is none, use document.

By attaching the event handler to #parent, events triggered by the children will be delegated to the parent and accepted if the targeted element matches your selector. This will take into account dynamically created elements and won't even attach an event handler to those children to begin with.

于 2013-05-16T00:44:56.917 回答