JQuery stopPropagation on .live() when handlers already exist and are bound

后端 未结 3 1280
情深已故
情深已故 2021-01-27 07:21

I\'m aware that live calls bubble up through the doccument and that is why I\'m having issues.

Unfortunately I\'m using third party libraries that bind elements and wou

相关标签:
3条回答
  • 2021-01-27 08:01

    use on delegate bound to outer and call e.stopPropagation() in inner click handler..this should dothe trick.

    try this updated

    $("#outer").bind('click',function(e){
      alert("outer clicked"); 
    });
    
    $('#outer').on('click',"#inner",function(e){
      e.stopPropagation();
      alert("inner clicked"); 
    
    });
    

    updated fiddle here

    0 讨论(0)
  • 2021-01-27 08:18

    As you've already remarked, event delegation hinges on event bubbling and the use of a static element. The issue is complicated because there's nothing between the <div id="inner"> and <div id="outer"> elements, but we can get around that.

    Set up a dynamic event handler for click events on the #inner element that's bound to #outer, and call event.stopImmediatePropagation() to prevent other event handlers from being executed. The downside is that this is dependent on the order in which the event handlers are bound, so your delegated event handler for #inner has to be bound before your static event handler for #outer.

    $('#outer').on('click', '#inner', function(e) {
        console.log('inner');
        e.stopImmediatePropagation();
    }).click(function(e) {
        console.log('outer');  
    });
    

    Take a look at this jsFiddle demo.

    0 讨论(0)
  • 2021-01-27 08:19

    U can use

    $("#outer").bind('click',function(e){
       alert("outer clicked"); 
    });
    $('#outer').on('click',"#inner",function(e){
        e.stopImmediatePropagation();
        alert("inner clicked"); 
    
    });
    
    0 讨论(0)
提交回复
热议问题