我对 Web 开发和 javascript 还很陌生。为了让我的网站更容易维护,我决定使用 Javascript 来从文本文件中读取“导航栏”并将其添加到每个页面的顶部。我现在想做的是创建一个函数,允许我指定链接和“链接深度”,以返回到我的页面的相对链接。这是函数:
function increaseLinkDepth(aLink, aDepth) {
var result = aLink;
for(i = 0;i < aDepth;i++) {
result = "../" + result;
}
return result;
}
现在,我有一些在桌面和移动设备上开发的经验,所以这是一个非常简单的功能。如果我像这样调用该函数:/increaseLinkDepth("index.html", 1)
,我希望得到以下结果:../index.html
。当我在网站上运行 javascript 时,我确实明白了这一点。现在,当我在以下代码中调用该函数时:
var anchors = document.getElementsByTagName("a");
for(i = 0;i < anchors.length;i++) {
var lAnchor = anchors[i];
var lAnchorLink = lAnchor.getAttribute("href");
if(lAnchorLink.substring(0, 4) != "http") {
var newLink = increaseLinkDepth(lAnchorLink, 1);
//alert(newLink);
lAnchor.setAttribute("href", newLink);
}
}
我最终陷入了某种无限循环,导致我必须重新启动浏览器。它应该寻找的链接是:
- index.html
- 事件.html
- about.html
它找到了所有三个,但循环发生在 about.html 链接上。我不确定我的代码中是否遗漏了某些内容(可能是看得太久了)。但我不知道我在哪里遇到这个问题。
现在,我确实明白这可能不是实现此目的的最佳方法,如果不是,请告诉我,这是我认为创建导航栏而无需更改的唯一方法每个页面的 HTML。
最佳答案
您从未在任一作用域中声明 i
,因此两个循环都会重置全局 i
变量。
为了避免全局污染,请务必将所有代码包装在 IIFE 中,并添加“use strict”
指令:
(function () {
"use strict";
...your code here...
}());
然后,浏览器控制台会告诉您,您正在这些范围内使用未声明的变量。
您提供的代码的净化版本将是:
(function () {
"use strict";
//variables declared at the top of the scope that they belong to
var anchors,
i,
lAnchor,
lAnchorLink,
newLink;
//function declarations follow variable declarations
function increaseLinkDepth(aLink, aDepth) {
var result,
i;
result = aLink;
for (i = 0; i < aDepth; i++) {
result = "../" + result;
}
return result;
}
//assignment and execution occurs after declarations
anchors = document.getElementsByTagName('a');
for (i = 0; i < anchors.length; i++) {
lAnchor = anchors[i];
lAnchorLink = lAnchor.getAttribute('href');
if (lAnchorLink.substring(0, 4) !== 'http') {
newLink = increaseLinkDepth(lAnchorLink, 1);
//alert(newLink);
lAnchor.setAttribute("href", newLink);
}
}
...more code...
}());
关于JavaScript 循环运行异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18594908/