我想通过单击每个孩子来获得祖父id
,用过event.target.parentNode.id
,但是它只是返回当前元素的父元素,所以当您单击每个子元素时,目标是获得#HereIAm
id小孩。有什么主意吗?
$(window).click(function(event) {
console.log(event.target.parentNode.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="HereIAm">
<ul>
<li><a>click me</a></li>
<li>click me</li>
</ul>
<span>click me</span>
<div>
<div>
<span>click me</span>
</div>
</div>
</div>
答案 0 :(得分:3)
鉴于HTML,一种选择是使用.closest
并使用选择器字符串div[id]
选择具有id
属性的最接近的祖先:
$(document).click(function({ target }) {
const closest = target.closest('div[id]');
if (closest) console.log(closest.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="HereIAm">
<ul>
<li><a>click me</a></li>
<li>click me</li>
</ul>
<span>click me</span>
<div>
<div>
<span>click me</span>
</div>
</div>
</div>
答案 1 :(得分:0)
如果您想通过点击点击我来获取 HereIAm ,则只需访问点击我的父母的父母
function getGrandParent(target){
if(target.parentElement.id === 'HereIAm'){
console.log(target.parentElement.id)
}else{
getGrandParent(target.parentElement);
}
}
<div id="HereIAm">
<ul>
<li onclick='getGrandParent(this)'><a>click me</a></li>
<li onclick='getGrandParent(this)'>click me</li>
</ul>
<span onclick='getGrandParent(this)'>click me</span>
<div>
<div>
<span onclick='getGrandParent(this)'>click me</span>
</div>
</div>
</div>