简体   繁体   中英

Onclick handlers with jquery

I have the following code

<div class="test-123">
   <p>Some Text</p>
   <div class="delete"></div>
   <div class="edit"></div>
</div>

The problem is that I have to have onclick jquery handlers for the three elements ( test-123, delete and edit ). I face the following problem. When I click on delete the onclick handler of test-123 is also executed after the onclick handler of the delete is finshed.

Is there a way to somehow prevent that?

You are looking for stopPropogation

event.stopPropagation()

http://api.jquery.com/event.stopPropagation/

$(function(){   
    $(".test-123").click(function(){
       alert("click on div"); 
    });      
    $(".delete,.edit").click(function(e){
       e.stopPropagation() 
       alert("click on Links"); 
    });    
});​

Comment out the e.stopPropagation line and see what happens.

Working demo : http://jsfiddle.net/Pjn3s/2/

See jQuery's event.stopPropagation . This will prevent additional listeners from firing. eg,

$("p").click(function(event){
  event.stopPropagation();
  // do something
});

As @paislee says is a problem with the propagation. Are you using the jQuery method "live", something like:

$('selector').live('click', function(){
//The actions
});

I think you should check the use of the method "delegate", that "forces" you to set the top parent for what elements must to be applied the closure. It is safer than any way (even click event).

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