jQuery事件性能:在父级上绑定单个事件或在每个子级上绑定单独的事件

jQuery event performance: Bind a single event on parent or individual events on each child?

本文关键字:事件 绑定 单独 jQuery 性能 单个      更新时间:2023-09-26

我有一个div,里面有大量的子div(大约4k-5k!)。每个子级都附加了一个'mousedown''mouseup'事件

我应该将这些事件附加到父项一次,然后使用$(e.target)选择子项吗?会有任何性能优势吗?如果有,为什么?

我认为使用jquery.on()将是理想的。

$("#divWithHugeAmountsOfChildDiv").on("mousedown", 
                                      ".childCLASSEStoMouseDown", 
                                      function()
{
  alert("Booya!");
});

你的html可能看起来像什么:

<body>
  <!-- lots of other elements -->
  <div id="divWithHugeAmountsOfChildDiv">
    <!-- lots of different type of elements -->
    <div class="childCLASSEStoMouseDown">Booya?</div>
    <!-- lots of different type of elements -->
  </div>
  <!-- lots of other elements -->
</body>

根据需要更改jQuery选择器。。。

原因在On方法的jQuery文档中得到了很好的解释。

使用jQuery的.on()已经为您做到了这一点。它将事件处理程序绑定到某个父级并检测子级事件。它具有优于.live().bind()的性能优势,以及类似.click()等的直接事件绑定,因为:

  • 与将事件绑定到document.live()不同,使用.on(),您负责绑定到哪个父级。

  • CCD_ 12被绑定到作为文档的根的CCD_。泡沫式上升的事件会走得更远。使用.on(),您可以找到最近的公共父级来绑定该事件。气泡将减少传播-的性能优势

  • 使用.on(),您只能将一个处理程序绑定到父级,这与.bind()和直接事件绑定不同,后者以每个元素为基础绑定事件,这对很多元素都不好。

  • .on()更容易记忆。

  • 当获取目标时,在.on()中,"this"始终是目标元素。永远不要担心跨浏览器甚至目标。jQuery为您做到了这一点。

所以这个代码中的"this":

$(element).on('click','someElement',function(){
    //the value of "this" in here is the DOM element target of the event
});

有这么多子div,您肯定应该将委托事件处理与jQuery的.on()一起使用。这将为父级提供一个事件处理程序,而不是为子级提供4000个事件处理。它的安装和初始化速度也会快得多。

如果您使用.on()的委托表格,您不必自己检查e.target,因为jQuery会为您检查。

以这种方式使用.on()的语法如下:

$('parentSelector').on('mousedown', 'child selector', function(e) {
    // code here
    // "this" will be the object that initiated the event
});

更多信息请参阅.on()的jQuery文档。