2017-03-02 62 views
-2

我需要檢查,如果一個div及其子被點擊檢測是否被點擊的div包括孩子的jQuery的

$('div').click(function(e){ 
    if(e.target.id == 'test') 
     alert(e.target.id); 
}); 

我需要測試的DIV是我的html代碼#TEST,這個代碼工作,但如果我點擊子元素它什麼都不做

我如何在我的代碼中有目標+孩子?

回答

1

您需要使用this(元素與事件附後),而不是event.target(與調用的事件元素),你應該使用ID選擇將事件處理程序附加即$('#test')

$('div').click(function(e) { 
 
    console.log(this.id); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="test"> 
 
    text 
 
    <button>1</button> 
 
</div>

0

這將工作,如果你點擊孩子,由於冒泡

$('#test').click(function(e){ 
     console.log(e.target); 
     //check if the target is the child you were expecting to be clicked 
}); 
0

如果您想檢查是否點擊了孩子+父母,然後將點擊事件放在孩子元素而不是父母上。您可以訪問子元素div .divclass或立即子div>.divclass