在 JQuery 中何时使用事件委托与事件处理是否有经验法则?

发布于 2024-07-26 23:30:08 字数 436 浏览 6 评论 0原文

我很困惑什么时候应该使用事件委托而不是开箱即用的 JQuery 事件处理。

我总是想使用事件处理程序,因为它在 JQuery 中非常简单:

例如:

$("button#submit").click(function () { 
      $(this).css("disabled", "true");
    });

事件委托编写起来其实并没有那么复杂:

$("button#submit").live("click", function() {
      $(this).css("disabled", "true");
});

但它看起来并不那么直观。

关于何时使用事件委托有一个简单的经验法则吗?我想我不太明白它的意义。

I'm confused about when you should use event delegation as opposed to out-of-the-box JQuery event handling.

I'm always tempted to use an event handler because it's so easy in JQuery:

For example:

$("button#submit").click(function () { 
      $(this).css("disabled", "true");
    });

Event delegation is not really that much more complex to write:

$("button#submit").live("click", function() {
      $(this).css("disabled", "true");
});

But it just doesn't seem as intuitive.

Is there a simple rule of thumb about when to use event delegation? I guess I don't really understand the point of it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一身软味 2024-08-02 23:30:09

当您要向页面动态添加需要分配该事件的元素时,请使用 .live() 。 (请注意,.live() 仅适用于选择器)

对于所有其他情况,请使用 .click() (或任何其他事件)

Use .live() when you will be dynamically adding elements to the page that need to have that event assigned to them. (note that .live() works only with selectors)

Use .click() (or whatever other event) for all other cases

哑剧 2024-08-02 23:30:09

您应该在以下情况下使用事件委托:

  • 当您想要跨多个元素处理同一事件时,例如,如果您有一个包含许多行的数据表,那么使用委托将使用更少的内存,并且比每行注册一个事件处理程序更快。
  • 当页面加载后元素动态添加到页面并且您想要处理这些新元素的事件时,例如向数据表添加行。

使用事件实用程序和事件委托来提高性能讨论了这一点更多(即使本文使用 YUI,其想法仍然适用)。

You should use event delegation in the following situations:

  • When you want to handle the same event across many elements, e.g. if you have a data table with many rows, using delegation will use much less memory and be faster than registering an event handler per row.
  • When elements are dynamically added to the page after page load and you want to handle events for these new elements, e.g. adding rows to a data table.

Using Event Utility and Event Delegation to Improve Performance disusses this some more (even though the article uses YUI the ideas are still applicable).

你爱我像她 2024-08-02 23:30:09

根据 this,当有大量绑定元素时,速度最重要。

According to this, it's all about speed when there are lots of bound elements.

世界等同你 2024-08-02 23:30:09

我发现我尽可能使用live。 这样,如果我稍后添加动态内容,我根本不需要更改代码。

I find I'm using live wherever possible. That way if I add dynamic content later, I don't have to change the code at all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文