The Click event handler unintentionally bubbles, even after jQuery's stopPropagation () call

I am trying to use different delegate click handlers for different elements in the "li" elements in the list. Example:

<ul id='myList'>
  <li>
    <p>First item.</p>
    <button>button1</button>
    <button>button2</button>
  </li>
  <li>
    <p>Second item.</p>
    <button>button1</button>
    <button>button2</button>
  </li>
</ul>

when the user presses button 1 (of any element), I want to capture this event and stop distributing (the same for button2 instances). The user, clicking on the parent element li, will be another handler:

$('#myList').delegate('li', 'click', function() {
    alert("You clicked a parent <li> item!");
});

$('#myList').delegate('button', 'click', function(event) {
    event.stopPropagation();
    event.stopImmediatePropagation();
    alert("You clicked a button (but which one?)!");
});

So, one problem is how do I have a delegate for button1 instances and another for button2 instances? The second delegate in the above example fires when the button is clicked, but event.stopPropagation () does not seem to work, since the handler of the parent element li is still called,

------ Update --------------

, event.stopImmediatePropagation(), , .

+3
4

, :

$('#myList').delegate('li', 'click', function(event) {
    if (!$(event.target).is('button')) {
        alert("You clicked a parent <li> item!");
    }
});
+1

, , jQuery, . :

(function(){
  var el = document.getElementsByTagName("li");
  var i = el.length;

  while (i--)
    el[i].onclick = function () {
      alert("You clicked a parent <li> item!");
    };

  el = document.getElementsByTagName("button");
  i = el.length;

  while (i--)
    el[i].onclick = function (event) {
      var e = event || window.event;

      e.stopPropagation();
      e.cancelBubble = true;
      alert("You clicked a button (but which one?)!");
    };

})();

, , ( IE). , , , .

: , id class es <button> s, , .

+1

event.stopImmediatePropagation(). , , , , .

0

, . delegate() , click - myList. , , , myList BUTTON LI.

LI BUTTON, LI , , BUTTON, .

0

Source: https://habr.com/ru/post/1751686/


All Articles