jquery .delegate and dynamic content

后端 未结 4 384
一向
一向 2020-12-22 12:38

I have to following HTML:

相关标签:
4条回答
  • 2020-12-22 12:48

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

    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

    Updated the demo to show it working with dynamic elements.


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

    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);
    });
    
    0 讨论(0)
  • 2020-12-22 12:54

    If you're using latest version of jQuery, correct code would be:

    $(document).on("click", ".liclass a", function(e) {
      e.stopPropagation();        
    });
    
    0 讨论(0)
  • 2020-12-22 13:00

    You need to call ".delegate" after each ajax request is completed in order for this to work.

    0 讨论(0)
  • 2020-12-22 13:06

    Event delegation means: The event already bubbled to a "higher level" element. It is not possible to stop the propagation to this element any more (because it already happened). The propagation can only be stopped for elements even higher in the hierarchy. It will not work at all if you bound the delegate to "document" already.

    0 讨论(0)
提交回复
热议问题