2017-03-02 46 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

相关问题