如何在鼠标悬停时获取元素的索引值
How to get index value of an element while onmouseover?
我试图在鼠标悬停时获取元素的索引号。
我可以用jQuery轻松做到这一点,但原生javascript是防弹的/:
这是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>
使用即时函数来修复当前迭代的 i 值:
for(i=0; i<ele.children.length;i++){
(function(i) {
ele.children[i].onmouseover = function() {
this.style.background='red';
alert(i);
}
}(i));
}
这是一个更新的小提琴。
那是
因为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));
演示
试试这个:
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);
}
相关文章:
- 如何在jQuery中获取元素的形式
- 通过id和class属性获取元素
- Javascript:Can't使用getElementById获取元素
- 使用jquery.html()获取元素本身的html
- 如何从iframe内部获取元素
- Javascript函数获取元素内容
- 使用模板后,使用Angular获取元素属性值
- 获取元素类名的部分
- 从JSON.parse获取元素
- 获取元素内部的缩写
- 在不引用文档的情况下使用AngularJS获取元素
- 如何获取元素's的title属性
- 使用Javascript,获取元素的方法是什么,基于打开和关闭标记之间的文本
- Javascript获取元素背景图像,但消除了“;url()”;
- Javascript:按类获取元素,但跳过某个类
- 当display:none时,getElementById()无法获取元素
- 我的ID获取元素不起作用
- 如何获取元素:使用javascript和CORS悬停背景
- 能够获取元素长度,但不能获取内部 HTML
- 如何使用jQuery在模板kendo UI中获取元素类