且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jquery .delegate和动态内容

更新时间:2023-12-05 08:29:16

在包含动态创建元素的任何内容上放置另一个委托处理程序,在本例中为 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

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