在JavaScript中列出样式

时间:2012-01-09 15:48:47

标签: javascript css list

我想使用JavaScript设置列表样式,以将类添加到活动的firstlevel列表项。因此,如果您点击“宣传单”,<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++;
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

你必须增加var i。你的进入无限循环!使用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++;
}