我正在尝试将 onmouseover/out 事件附加到页面上的所有 anchor 标记(想法是在 onmouseover 时将其置于其之下并在 onmouseout 时将其删除)。
我做了以下代码。它将事件附加到所有 anchor ,但当鼠标悬停在任何 anchor 上时,它始终只为页面中的最后一个 anchor 添加下划线。
知道,可能出了什么问题吗?
window.onload = function () {
var elArray = document.getElementsByTagName("a");
if (elArray != null && elArray.length > 0) {
for (var count = 0; count < elArray.length; count++) {
var el = elArray[count];
if (el.addEventListener) {
el.addEventListener("mouseover", function () {
el.style.textDecoration = 'underline'
}, false);
el.addEventListener("mouseout", function () {
el.style.textDecoration = 'none'
}, false);
} else {
el.attachEvent('onmouseover', function () {
el.style.textDecoration = 'underline'
});
el.attachEvent('onmouseout', function () {
el.style.textDecoration = 'none'
});
}
} //for
} //if
}; //end of window.onload
最佳答案
这是由于范围问题造成的; el
范围不限于 for
的每次迭代循环,它的作用域是整个函数,所以一旦for
循环已完成执行el
指的是最后一个元素。自 el
事件处理函数内部是同一个变量,它们只会影响最后一个 <a>
页面上的元素。
但是,没有必要为此使用 JavaScript,使用 CSS 已经可以实现同样的事情相当长一段时间了。以下内容应该有效:
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
如果您绝对想使用 JavaScript,那么您需要创建一个闭包来修改 el
的范围使用立即调用的函数表达式:
window.onload = function () {
var elArray = document.getElementsByTagName("a");
if (elArray != null && elArray.length > 0) {
for (var count = 0; count < elArray.length; count++) {
var el = elArray[count];
(function(el) {
// el in here is different to el outside since the parameter shadows it
// you could give them different names - or not declare an el variable outside - to make the difference clearer
if (el.addEventListener) {
el.addEventListener("mouseover", function () {
el.style.textDecoration = 'underline'
}, false);
el.addEventListener("mouseout", function () {
el.style.textDecoration = 'none'
}, false);
} else {
el.attachEvent('onmouseover', function () {
el.style.textDecoration = 'underline'
});
el.attachEvent('onmouseout', function () {
el.style.textDecoration = 'none'
});
}
})(el);
} //for
} //if
}; //end of window.onload
el
的范围在该匿名函数内部进行更改,使其确实引用 el
的值对于 for
的每次迭代循环。
关于javascript - 将鼠标事件附加到 anchor : Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16034625/