如何在onmouseover上获取元素的索引值?

时间:2013-01-21 22:19:16

标签: javascript indexing click this onmouseover

我试图在onmouseover时获取元素的索引号 我可以使用jQuery轻松完成此操作,但原生javascript是防弹/:

Here is jsFiddle

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>

3 个答案:

答案 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);

DEMO

或使用闭包:

ele.children[i].onmouseover = (function (index) {
    return function () {
        this.style.background = 'red';
        alert(index);
    };
}(i));

DEMO

答案 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);
}