gpt4 book ai didi

jquery - 为什么我的 jQuery 警报显示两次?

转载 作者:行者123 更新时间:2023-12-01 00:33:46 24 4
gpt4 key购买 nike

我正在使用 jQuery。当警报列表的 ID 显示两次而不是一次时,我遇到了问题。

列表:

<ul id="testnav">
<li> <a href="#">Page 1</a></li>
<li> <a href="#">Page2..</a>
<ul id="subnav">
<li id="content_1"><a href="#"> Page3</a></li>
</ul>
</li>
</ul>

代码:

$("li").click(function(){
var current_id = $(this).attr('id');
alert(current_id);
// These alert two times, one is empty and another one is content_1
});

为什么代码警报会重复两次?如何让它执行一次?

最佳答案

$("li").click() 正在将点击事件应用于页面上的所有 LI。

当您点击时

<li> <a href="#">Page2..</a>
<ul id="subnav">
<li id="content_1"><a href="#"> Page3</a></li>
</ul>
</li>

您实际上单击了外部 LI 和最内部的 LI,这将导致事件触发两次。外层 LI 没有 ID,因此为空,内层 LI 的 ID 为“content_1”,因此显示。

这有意义吗?

关于jquery - 为什么我的 jQuery 警报显示两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/512010/

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