最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery stop calling other handler - Stack Overflow

programmeradmin0浏览0评论

Let's say I have labels and I attach two click events to it:

$('#l1').bind('click',function(){
 alert('label clicked');
}
$('#l2').bind('click',function(){
 alert('label2 clicked');
}
$('#l3').bind('click',function(){
 alert('label3 clicked');
}

$('label').bind('click',function(){
 if($(this).hasClass('disabled')
return false
}
<label id='l1'>hi</label>
<label id='l2' class="disabled">bye</label>
<label id='l3'>hi</label>

Now I don't want the alert to be displayed when the label that has class disabled is clicked. Is it possible to do that?

Note : alert is just a dummy thing.. I am performing a set of actions instead of that.. each different on basis of the actual label

Let's say I have labels and I attach two click events to it:

$('#l1').bind('click',function(){
 alert('label clicked');
}
$('#l2').bind('click',function(){
 alert('label2 clicked');
}
$('#l3').bind('click',function(){
 alert('label3 clicked');
}

$('label').bind('click',function(){
 if($(this).hasClass('disabled')
return false
}
<label id='l1'>hi</label>
<label id='l2' class="disabled">bye</label>
<label id='l3'>hi</label>

Now I don't want the alert to be displayed when the label that has class disabled is clicked. Is it possible to do that?

Note : alert is just a dummy thing.. I am performing a set of actions instead of that.. each different on basis of the actual label

Share Improve this question edited Nov 13, 2022 at 20:33 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Nov 29, 2011 at 11:28 Gaurav ShahGaurav Shah 5,2797 gold badges44 silver badges74 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 22

If multiple event handlers are bound to the same element for the same event the handlers are called in the order they were bound. If you call event.stopImmediatePropagation() within a particular handler it will stop subsequent handlers being called.

So modify your $('label').bind() as follows:

$('label').bind('click',function(event){
   if($(this).hasClass('disabled') {
      event.stopImmediatePropagation();
      return false;
   }
}

and move that up above your other .bind() calls. Then that particular handler will execute first and have the chance to prevent the other handlers from executing.

(Note that .stopImmediatePropagation() is not the same as .stopPropagation()] - the latter stops the event bubbling up the DOM tree but doesn't stop other handlers on the same element.)

发布评论

评论列表(0)

  1. 暂无评论