gpt4 book ai didi

javascript - 函数 e 中的子项?

转载 作者:行者123 更新时间:2023-11-28 13:54:23 24 4
gpt4 key购买 nike

<div id="home">
<div id="second"></div>
</div>

#home {
width: 100px;
height: 100px;
background-color: red;
}

#second {
width: 20px;
height: 20px;
background-color: green;
}

$(window).click(function(e) {
if(e.target.id == 'home'){
alert('This is div home!');
}

});

现在,如果我单击绿色 div,则这不起作用,但该 div 为红色 div。是否可以为此自动添加所有 child div id 主页?如果这个 div 有 100 个子元素,那么我必须添加 100 个 if?

最佳答案

您需要检查目标元素是否位于#home div 内:

$(document).click(function(e)
{
if(e.target.id == 'home' || $(e.target).closest('#home').length)
{
alert('This is div home!');
}
});

这是 fiddle :http://jsfiddle.net/6sY49/

关于javascript - 函数 e 中的子项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8875429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com