2012-11-09 90 views
0

我有两个div,其他的一个内:选择父DIV的时候,我只焕选择儿童DIV

<div id="parent"> 
    <div id="children"> 
     Click me 
    </div> 
</div> 

当我点击了孩子的div使用jQuery,父也被点击了。

$(function() { 
    $("div").click(function(){ 
     alert("The id of the selected item is: " + $(this).attr("id")); 
    }); 
});​ 

我该怎么做才能避免这种情况?这里是我的jsfiddle:http://jsfiddle.net/gzpPB/1/

+0

为什么不只是针对其ID孩子的div? – j08691

+0

嘿,@GalloPinto,如果你可以选择这个问题的答案可能会很好......谢谢! – exoboy

回答

2

最健壮的解决方案是简单地给所有点击接受的DIV元素一个特定的类。这样,无论在哪里,或者嵌套了多深,只有具有“按钮”类的元素才会被触发。

NEW CODE:

<div id="parent"> 
    <div id="children" class="button"> 
     Click me 
    </div> 
</div> 


$(function() { 
    $(".button").click(function(){ 
     alert("The id of the selected item is: " + $(this).attr("id")); 
    }); 
});​ 

如果您使用jQuery 1.8或更高版本,你需要做这种方式:

$(function() { 
     $(document).on('click', ".button", function(){ 
      alert("The id of the selected item is: " + $(this).attr("id")); 
     }); 
    });​ 
2

在您选择更具体:

$("#children") instead of $("div") 
0

Becoz你只是针对页面上的div元素。使用e.target来定位特定的div。 也e.stopPropagation()

$(function() { 
     $("div").click(function(e){ 
      if(e.target.id == 'children'){ 
       e.stopPropagation(); 
       alert("The id of the selected item is: " + $(this).attr("id")); 
      } 
     }); 
    }); 

Check Fiddle

0

使用.stopPropagation()像:

$(function() { 
    $("div").click(function(e){ 
     e.stopPropagation(); 
     alert("The id of the selected item is: " + $(this).attr("id")); 
    }); 
});​ 

jsFiddle example

您的代码警报两个div的,当你cli来因为bubbling因子ck。对孩子的点击传到父级,然后再次触发laert,因为你的jQuery的目标是所有的div,而不是特定的div。您只能通过使用$("#children")来针对只有子div。但是,您也可以使用stopPropagation()来阻止冒泡,这可以让您的警报在单击任何div时运行,而不仅仅是一个特定的div。