Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 循环以匹配指向同一页面的两个URL_Javascript_Html_Loops - Fatal编程技术网

Javascript 循环以匹配指向同一页面的两个URL

Javascript 循环以匹配指向同一页面的两个URL,javascript,html,loops,Javascript,Html,Loops,在我的网站上,以下两个URL都指向同一页面: 网站URL 索引页URL 我有一个循环来突出显示导航菜单中的当前页面链接: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Index</title> <style> ul { list-style-type: none;

在我的网站上,以下两个URL都指向同一页面:
网站URL
索引页URL

我有一个循环来突出显示导航菜单中的当前页面链接:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Index</title>
    <style>
        ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
        }
        li {
            display: inline;
        }
        a.current {
            background: red;
        }
    </style>
</head>

<body>
    <ul>
        <li><a href="https://googledrive.com/host/0B5jOXzxlxbMhaERteVA4cmJwdDg/index.html">Index</a>
        </li>
        <li><a href="https://googledrive.com/host/0B5jOXzxlxbMhaERteVA4cmJwdDg/news.html">News</a>
        </li>
        <li><a href="https://googledrive.com/host/0B5jOXzxlxbMhaERteVA4cmJwdDg/contact.html">Contact</a>
        </li>
        <li><a href="https://googledrive.com/host/0B5jOXzxlxbMhaERteVA4cmJwdDg/about.html">About</a>
        </li>
    </ul>
    <h1>Index</h1>
    <script>
        for (var i = 0; i < document.links.length; i++) {
            if (document.links[i].href == document.URL) {
                document.links[i].className = 'current';
            }
        }
    </script>
</body>

</html>

指数
保险商实验室{
列表样式类型:无;
保证金:0;
填充:0;
}
李{
显示:内联;
}
a、 当前{
背景:红色;
}
指数 对于(var i=0;i

现在的问题是,当您转到主站点URL时,它没有突出显示索引链接:

您可以测试当前URL是否以“.html”结尾,如果不是,则在for循环之前添加“index.html”:

    var currentURL = document.URL;
    if (currentURL.slice(-5) != ".html") {
        currentURL = currentURL.replace(/\/?$/,"/index.html");
    }
    for (var i = 0; i < document.links.length; i++) {
        if (document.links[i].href === currentURL) {
            document.links[i].className = 'current';
        }
    }
var currentURL=document.URL;
if(currentURL.slice(-5)!=“.html”){
currentURL=currentURL.replace(/\/?$/,“/index.html”);
}
对于(var i=0;i
for(var i=0;i
谢谢你的回答,但我只是想出了一个更简单的方法。
for (var i = 0; i < document.links.length; i++) {
    if (document.links[i].href == document.URL || document.links[i].href == document.URL + 'index.html') {
        document.links[i].className = 'current';
    }
}