HTML CODE:
<li id="list_id">List_text<img src='image.jpg' id="img_id"></li>
jQuery Function:
$("#list_id").live('click' , function(){
alert(开发者_StackOverflow中文版'List is clicked');
});
$("#img_id").live('click' , function(){
alert('Image is clicked');
});
Once i click image its parent li function is also triggered. Give me a solution to solve this. I need to trigger img event only when i click img element and need to trigger li event when i click li element.
You need .stopImmediatePropagation()
here to be safe, since the event handler is at the same level (.live()
event handlers live on document
by default), like this:
$("#list_id").live('click' , function(){
alert('List is clicked');
});
$("#img_id").live('click' , function(e){
e.stopImmediatePropagation();
alert('Image is clicked');
});
You can test it here.
Note, this doesn't do the job if you're on jQuery < 1.4.3, for that you also need to check if it's stopped using e.isImmediatePropagationStopped()
, like this:
$("#list_id").live('click' , function(e){
if(e.isImmediatePropagationStopped()) return;
alert('List is clicked');
});
$("#img_id").live('click' , function(e){
e.stopImmediatePropagation();
alert('Image is clicked');
});
$("#img_id").live('click' , function(){
alert('Image is clicked');
return false;
});
精彩评论