gpt4 book ai didi

javascript - 函数点击 li 元素

转载 作者:行者123 更新时间:2023-11-30 17:03:00 24 4
gpt4 key购买 nike

我有一个包含 li 元素的菜单,在单击我喜欢的元素之一后运行一个函数,单击并显示 id 为 li 元素的警报。

JS

  <script type="text/javascript">
$("#mainmenu li").click(function() {
alert(this.id);
});
</script>

HTML

    <div id="menu1">
<ul id="mainmenu">
<li><a href="#">Choose the first map <i class="arrow"></i></a>
<ul>
<li><a href="#">Category 1<i class="arrow"></i></a>
<ul>
<li class="div1clear" id="firstIDtoDisplay" data-path="contents/work/cycling1.html"><a href="#">% of employees cycling to work</a></li>
</ul>
</li>
<li><a href="#">Ethnic maps<i class="arrow"></i></a>
<ul>
<li class="div1clear" id="secoundIDtoDisplay" data-path="contents/ethnic/white_british1.html"><a href="#">% of White British residents</a></li>
<li class="div1clear" id="thirdIDtoDisplay" data-path="contents/ethnic/white_tot1.html"><a href="#">% of White residents</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>

 <script type="text/javascript">
$("#mainmenu li").click(function() {
alert(this.id);
});
</script>



<div id="menu1">
<ul id="mainmenu">
<li><a href="#">Choose the first map <i class="arrow"></i></a>
<ul>
<li><a href="#">Category 1<i class="arrow"></i></a>
<ul>
<li class="div1clear" id="firstIDtoDisplay" data-path="contents/work/cycling1.html"><a href="#">% of employees cycling to work</a></li>
</ul>
</li>
<li><a href="#">Ethnic maps<i class="arrow"></i></a>
<ul>
<li class="div1clear" id="secoundIDtoDisplay" data-path="contents/ethnic/white_british1.html"><a href="#">% of White British residents</a></li>
<li class="div1clear" id="thirdIDtoDisplay" data-path="contents/ethnic/white_tot1.html"><a href="#">% of White residents</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>

不幸的是,点击后没有任何反应。控制台也没有错误。可能错误出在 JS 代码中,您知道什么是问题吗?

最佳答案

https://jsfiddle.net/pgsf6fot/

$(document).ready(function() { 
$("#mainmenu li").click(function() {
alert( $(this).attr('id') );
});
});

关于javascript - 函数点击 li 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28526272/

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