如何通过侦听器引用数组中的当前dom元素来更改活动

How to refer to current dom element in array for changing activity via the listener

本文关键字:元素 dom 活动 侦听器 何通过 引用 数组      更新时间:2023-09-26

目前,我正在循环通过我所有的图像,并使他们的onmouseover/onmouseout事件改变他们的图像与for循环。

 var arrows = document.getElementsByClassName('arrow');
 for (var i = 0; i < arrows.length; i++) {
     arrows[i].onmouseover = arrows[i] + ".src = 'images/downarrow_hover.gif';";
     arrows[i].onmouseout = arrows[i] + ".src = 'images/downarrow.gif';";
 }

它不工作,我这样做对吗?

您必须将功能分配给onmouseoveronmouseout

var arrows = document.getElementsByClassName('arrow');
for (var i = 0; i < arrows.length; i++) {
    arrows[i].onmouseover = function () {
        this.src = 'images/downarrow_hover.gif';
    };
    arrows[i].onmouseover = function () {
        this.src = 'images/downarrow.gif';
    };

对于它的价值,如果你能负担得起,你应该看看jQuery,这使得做这样的事情很容易:

$('.arrow').hover(
    function () { $(this).attr('src', 'images/downarrow_hover.gif'); },
    function () { $(this).attr('src', 'images/downarrow.gif'); });