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

javascript - jQuery: clicking nested elements - Stack Overflow

programmeradmin0浏览0评论

I have the following markup

<ol>
    <li class="ListItem">
        <span class="sub">@qItem.CategoryText</span>
        <input type="image" src=".png" width="30" class="deleteIcon" name="QuestionId" value="@qItem.Id" />
    </li>
</ol>

and the following script

$(".ListItem").click(function(){
doActionA();
});

$(".deleteIcon").click(function(){
doActionB();
});

When I click in image, it also triggers click of ListItem. I understand this is because image is inside ListItem. but I want ListItem's click not to be fired when image is clicked. Is there any way to do that ?

I have the following markup

<ol>
    <li class="ListItem">
        <span class="sub">@qItem.CategoryText</span>
        <input type="image" src="http://icons.iconarchive.com/icons/tatice/just-bins/256/bin-red-full-icon.png" width="30" class="deleteIcon" name="QuestionId" value="@qItem.Id" />
    </li>
</ol>

and the following script

$(".ListItem").click(function(){
doActionA();
});

$(".deleteIcon").click(function(){
doActionB();
});

When I click in image, it also triggers click of ListItem. I understand this is because image is inside ListItem. but I want ListItem's click not to be fired when image is clicked. Is there any way to do that ?

Share Improve this question asked Jan 8, 2013 at 6:27 Bilal FazlaniBilal Fazlani 6,96710 gold badges46 silver badges94 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 24
$(".deleteIcon").click(function(e){
    doActionB();
    e.stopPropagation();
});

You need to use event.stopPropagation() to prevents the event from bubbling up the DOM tree.

$(".deleteIcon").click(function(event){
    event.stopPropagation()
    doActionA();    
});

The event you binded with delete icon is firing the parent event binding with ListItem, so you need to stop propagation for parent event when child is source of event.

$(document).on("click", ".deleteIcon", function() {
  doActionB();
});

This method is the only one I found to work with nested elements, especially those generated by a library such as Pivottable (https://github.com/nicolaskruchten/pivottable)

$(".deleteIcon").click(function(){
    doActionA();
    return false;  
});

Use .one(), as directed in the JQuery documentation.

发布评论

评论列表(0)

  1. 暂无评论