5

I have a problem with jQuery clickwhen the selector is a for a divthat is on top of another divas seen here..

html

<div id="parent">
 <div id="child">
 </div>
</div>​

css

#parent{
 background-color:red;
 width:100px;
 height:100px;   
 position:relative;
}


#parent:hover #child {
 display:block;

}
#child{
 background-color:yellow;  
 width:10px;
 height:10px;  
 border: 1px solid black;
 position:absolute;
 display:none;
 bottom:0;
 right:0;
}

js

$("#parent").bind("click", function() {
    alert('you clicked on red');
});

$("#child").bind("click", function() {
    alert('you click on yellow');
});​

如果您单击红色#parent,它会给出正确的警报。如果单击黄色#child,它会给出黄色警报和红色警报。

jsfiddle

有没有办法来解决这个问题?

4

1 回答 1

7

使用 jQuery 的.stopPropagation()

$("#parent").bind("click", function() {
  alert('you clicked on red');
});

$("#child").bind("click", function(e) {
  e.stopPropagation();
  alert('you click on yellow');  
});​

http://jsfiddle.net/qTdkt/4/

于 2012-12-09T19:06:09.567 回答