为什么鼠标悬停在javascript中不能与类一起使用,但可以在id上使用?
例如,
window.onload = function() {
var myIcon = document.getElementsByClassName('myIcon'); //does not work
myIcon.onmouseover = function() {
// do something
return false;
};
};
but
window.onload = function() {
var myIcon = document.getElementsByID('myIcon'); //works
myIcon.onmouseover = function() {
// do something
return false;
};
};
您有两个同名的变量,即重新声明和重新分配myIcon
。另外,getElementsByID
不是函数,getElementById
或者getElementsById
是。getElementsById
然后返回带有元素“数组”的NodeList。最后,getElementsByClassName
还返回一个NodeList。两者都是类似数组的,因此您必须像对待数组一样对待它。
这是JSFiddle上的一个示例,请注意,getElementsByClassName
该示例仅适用于class的第一个元素myIcon
。您可以使用for循环遍历所有元素并更改其侦听器。
var myIcon_class = document.getElementsByClassName('myIcon')[0]; //note, gets first element
var myIcon = document.getElementById('myIcon')
myIcon.onmouseover = function() {
alert("hovered on ID!");
return false;
};
myIcon_class.onmouseover = function() {
alert("hovered on class!");
return false;
};
<span id="myIcon">Id span!</span>
<span class="myIcon">Class span!</span>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句