gpt4 book ai didi

javascript - JavaScript 中的列表样式

转载 作者:太空宇宙 更新时间:2023-11-04 05:13:13 25 4
gpt4 key购买 nike

我想使用 JavaScript 为列表设置样式,以将类添加到事件的第一级列表项。因此,如果您单击“传单”,<li><a href="#">Downloads &raquo;</a>变成 <li class="active"><a href="#">Downloads &raquo;</a> .

HTML

<ul id="navmenu">
<li><a href="#">Downloads &raquo;</a>
<ul>
<li><a href="downloads_flyer.php">Flyer</a></li>
<li><a href="downloads_jahresberichte.php">Jahresberichte</a></li>
<li><a href="downloads_banner.php">Banner</a></li>
</ul>
</li>
<li><a href="presse.php">Pressecenter</a></li>
<li><a href="kontakt.php">Kontakt</a></li>
</ul>

JavaScript(更新)

var i = 0;
var url = "<?php echo end(explode("/", $_SERVER["SCRIPT_NAME"])); ?>";
var liste = document.getElementById("navmenu").getElementsByTagName("li");
while(i < liste.length) {
var topList = liste[i];
var topLink = liste[i].getElementsByTagName("a")[0];
if (topLink.href.substr((topLink.href.length - 1), 1) != "#" // To avoid matching the 'Downloads' link.
&& topLink.href.indexOf(url) > 0)
{
topList.className = "active";
}
i++;
}

如您所见,它将“事件”添加到包含链接的 LI,但它应该添加到顶层 LI。我怎样才能让脚本正确运行 - 我的错误是什么?

最终解决方案

var i = 0;
var url = "<?php echo end(explode("/", $_SERVER["SCRIPT_NAME"])); ?>";
var liste = document.getElementById("navmenu").getElementsByTagName("li");
while(i < liste.length) {
var topLink = liste[i].getElementsByTagName("a")[0];
if (topLink.href.substr((topLink.href.length - 1), 1) != "#" // To avoid matching the 'Downloads' link.
&& topLink.href.indexOf(url) > 0)
{
if(topLink.parentNode.parentNode.parentNode.tagName == "LI") {
topLink.parentNode.parentNode.parentNode.className = "active";
} else {
topLink.parentNode.className = "active";
}
}

i++;
}

谢谢大家的帮助!

最佳答案

您必须递增 var i。你的 while 进入无限循环!不要使用 document.URL,请尝试使用 $_SERVER['SCRIPT_NAME']:

var i = 0;
var url = "<?php echo end(explode("/", $_SERVER["SCRIPT_NAME"])); ?>";
var liste = document.getElementById("navmenu").getElementsByTagName("li");
while(i < liste.length) {
var topLink = liste[i].getElementsByTagName("a")[0];
if (topLink.href.substr((topLink.href.length - 1), 1) != "#" // To avoid matching the 'Downloads' link.
&& topLink.href.indexOf(url) > 0)
{
topLink.parentNode.parentNode.parentNode.className = "active";
}

i++;
}

关于javascript - JavaScript 中的列表样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8791093/

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