delegate和动态内容

delegate和动态内容

本文介绍了jquery .delegate和动态内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须关注HTML:

<ul class="ulclass">
   <li class="liclass">
      ...some more nesting
           <a href="somelink">somelink</a>
      ....close nesting
   </li>
   <li class="liclass">
   ...

</ul>

liclass类中的每个li上都有一个click事件,所以我停止冒泡锚点(可能是< div> 在.liclass中):

There is a click event on each li from the class "liclass", so I stop the bubbling from the anchor with (presumably <div> is inside of .liclass):

$(".liclass div").delegate("a", "click", function(e) {
          e.stopPropagation();
});

现在我添加更多< li class =liclass> 使用Ajax .load。 stopPropagation适用于静态.liclass,但不适用于动态添加。
假设加载页面时,< ul class =ulclass> 的代码存在。
你能不能让我知道改变.delegate是如何阻止动态添加的.liclass冒泡的。

Now I add more <li class="liclass"> with Ajax .load. The stopPropagation works for the static ".liclass" but not for the dynamically added.Assume that the code for <ul class="ulclass"> is there when the page is loaded.Can you please let me know how the change .delegate in order to stop the bubbling for the dynamically added .liclass.

推荐答案

在包含动态创建元素的任何内容上放置另一个委托处理程序,在本例中为 ul ,用于停止传播。

Place another delegate handler on whatever contains the dynamically created elements, in this case the ul, to stop the propagation.

$("ul.ulclass").delegate(".liclass div", "click", function(e) {
          e.stopPropagation();
});

$("ul.ulclass").delegate(".liclass", "click", function(e) {
          // main code for each li element
});

因为它们是同一元素上的委托方法,所以 e。 stopPropagation()应该可以防止处理程序,即使事件已经冒泡了。

Because they're both delegate methods on the same element, the e.stopPropagation() should work to prevent the handler even though the event has already bubbled up.

JSFIDDLE DEMO

更新了要显示的演示它使用动态元素。

另一种方法是简单地将处理程序直接绑定到动态创建的 div 元素。

An alternative would be to simply bind handlers directly to your dynamically created div elements.

因此,如果您使用 .load(),我认为您正在消除旧内容和用新的替换它。在这种情况下,在回调中,只需选择div,然后重新绑定处理程序。

So if you're using .load(), I assume you're wiping out the old content and replacing it with new. In that case, in the callback, just select the divs, and rebind the handler.

$("ul.ulclass").load('/whatever/', function() {
      // shortcut to binding a handler with stopPropagation and preventDefault
    $(this).find('li.liclass div').bind('click', false);
});

这篇关于jquery .delegate和动态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:33