简体   繁体   中英

stopPropagation() of a different event

How can I listen to a change event on a checkbox without triggering a click event on its container?

<label><input type="checkbox"> Hello world</label>

I want to trigger an action on the checkbox's change event, but I don't want it to bubble up to a click event on the label.

(function ($) {
    $('input').change(function (v) {
        v.stopPropagation();
    });

    $('label').click(function () {
        alert('You should not see this message if you click the checkbox itself!');
    });
})(jQuery);

http://jsfiddle.net/r49PA/

Any ideas? Thanks!

You can stop propagation on click event instead of change event since you bind click event for the parent label :

$('input').click(function (v) {
    v.stopPropagation();
});

Updated Fiddle

The issue is that two events are triggered when you click the checkbox -- a change and a click . You're only catching the change , so the click isn't ever being told to stop propagation. You need to either add a second handler on the checkbox for click events, or combine one handler to catch both types, like this:

$('input').on('change, click', function (v) {
    v.stopPropagation();
});

Here's a jsFiddle demonstrating a combined handler: http://jsfiddle.net/r49PA/4/

With plain javascript you can do something like this:

var stopPropagation = false;    

selector.addEventListener('mousedown', function(event) { 
  // simulating hold event
  setTimeout(function() {
    stopPropagation = true;

    // do whatever you want on the `hold` event

  })
}

selector.addEventListener('click', function(event) { 
  if (stopPropagation) { event.stopPropagation(); return false; }

  // regular event code continues here...

}

Since mousedown and click events are overlapping, we want the click event to not be triggered when we are trying to get the hold state. This little helper flag variable stopPropagation does the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM