2015-10-17 123 views
1

正如我的標題所解釋的那樣,我怎樣才能讓父母可以點擊?如何使只有父div可點擊?

HTML

<div id="canvas" onclick="closeCanvas()"> 
    <img src="image.png" /> 
</div> 

JQUERY

function closeCanvas(){ 
    $("#canvas").fadeOut(300); 
} 

我的問題是,當我點擊 「圖像」,功能closeCanvas()也被觸發。我如何才能讓父母,#canvas,可觸發?

+1

一下添加到'img','的onclick =」 event.stopPropagation()「' – Tushar

+0

另請參閱'event bubbling'。檢查[什麼是事件冒泡和捕獲](http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-ampuring) – Tushar

回答

3

添加StopPropagation到img是否意味着點擊img將無法​​通過單擊事件給父DIV:

<div id="canvas" onclick="closeCanvas()"> 
    <img src="image.png" onClick="event.stopPropagation()" /> 
</div> 
+0

Shoekran。有用! – Mossawi

3

$(document).ready(function(){ 
 
    $('canvas').click(function(e){ 
 
     console.log(e); 
 
    }); 
 

 
    
 
}); 
 

 
function closeCanvas(event){ 
 
    if(event.target.id== "canvas") 
 
    $("#canvas").fadeOut(300); 
 
}
#canvas{ 
 
    height:100px; 
 
    width:100px; 
 
    background-color:red; 
 

 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="canvas" onclick="closeCanvas(event)"> 
 
    <img src="image.png" /> 
 
</div>