我试图在onmouseover时获取元素的索引号 我可以使用jQuery轻松完成此操作,但原生javascript是防弹/:
var ele = document.getElementsByClassName('sample')[0];
for(i=0; i<ele.children.length;i++){
ele.children[i].onmouseover = function() {
this.style.background='red';
alert(i);//can't get the value
}
}
<ul class="sample">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
答案 0 :(得分:4)
使用立即函数来修复当前迭代的i值:
for(i=0; i<ele.children.length;i++){
(function(i) {
ele.children[i].onmouseover = function() {
this.style.background='red';
alert(i);
}
}(i));
}
这是更新的fiddle。
答案 1 :(得分:2)
那是因为i
已被覆盖,将其存储在属性中:
ele.children[i].onmouseover = function() {
this.style.background='red';
alert(this.getAttribute('data-index'));
};
ele.children[i].setAttribute('data-index', i);
或使用闭包:
ele.children[i].onmouseover = (function (index) {
return function () {
this.style.background = 'red';
alert(index);
};
}(i));
答案 2 :(得分:1)
试试这个:
function callback(i) {
return function() {
this.style.background = "red";
alert(i);
};
}
for (var i = 0; i < ele.children.length; i++) {
ele.children[i].onmouseover = callback(i);
}