2012-12-04 38 views
0

http://jsfiddle.net/aQb9H/ 要做到這一點,最好的方法是什麼?在點擊孩子時不要激活父母。現在點擊這個孩子時都會被激活。如何在點擊孩子時不激活母親?

<!DOCTYPE html> 
<head> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<script> 
$(document).ready(function(){ 

    $('#child').click(function(){ 
     $('#output').append('Child is activated ||') 
    }) 

    $('#mother').on('mousedown',function(){ 
     $('#output').append('Mother is activated ||') 
    }) 


}) 
</script> 
</head> 

<style> 
#mother,#child,#output{ 
display:block; 
color:white; 
font-weight:bold; 
cursor:pointer; 
} 
#mother{ 
width:100px;height:100px; 
padding:30px; 
margin:20px; 
background-color:purple; 
} 
#child{ 
width:100px;height:100px; 
background-color:orange; 
} 
#output{ 
    width:300px;height:100px; 
border:2px solid red; 
color:black;  
} 
</style> 
<body> 
    <h1>Click Child, I don't want to activate mother when clicking child</h1> 
<div id='mother'> 
    Mother 
    <div id='child'>Child</div> 

</div> 
<div id='output'> Output: </div> 

</body> 
</html> 
+0

注意,一個'click'事件是'mousedown'然後'在相同的元素mouseup',那麼你的'mousedown'處理程序在甚至確定是否將發生「點擊」之前觸發。 – nnnnnn

回答

1

試試這個

DEMO

$('#child').on('mousedown', function(e){ 
    e.stopPropagation(); 
    $('#output').append('Child is activated ||') 
}) 

$('#mother').on('mousedown',function(){ 
    $('#output').append('Mother is activated ||') 
}) 
+1

哦......我必須在mousedown上同時使用或者同時使用click()? – FatDogMark

+0

好吧,它真的有用,我打算設置一堆變量和條件,我知道有簡單的方法 – FatDogMark