在循环中独立鼠标悬停addEventListener

时间:2017-04-22 14:29:00

标签: javascript for-loop mouseover addeventlistener

我想在所有带有“object”类的元素上添加一个“addEventListener”,当鼠标移过来更改对象的边缘时。

但我总是选择循环中的最后一个元素。

有代码:

<div class='objeto' id='obj1'>obj1</div>
<div class='objeto' id='obj2'>obj2</div>
<div class='objeto' id='obj3'>obj3</div>
<script type='text/javascript'>
    var i;
    var objetos = document.getElementsByClassName('objeto');
    for (i = 1; i<objetos.length+1; i++){
         id = 'obj'+i; 
         document.getElementById(id).addEventListener('mouseover',function(){
                  borderObject(id);
         }, false);
    };
    function borderObject(id){ document.getElementById(id).style.border="4px solid red"; }
</script>
PD:我知道CSS存在:悬停,但我想用Javascript

3 个答案:

答案 0 :(得分:0)

您需要将正确的ID传递给函数,此borderObject(id);始终传递最后一个ID,您需要传递当前点击的项目。

示例

&#13;
&#13;
var i;
var objetos = document.getElementsByClassName('objeto');
for (i = 1; i < objetos.length + 1; i ++ ){
    id = 'obj'+i;
    document.getElementById(id).addEventListener('mouseover',function(e){
        borderObject(e.target.id);
    }, false);
};
function borderObject(id){ 
    document.getElementById(id).style.border = "4px solid red"; 
}
&#13;
<div class='objeto' id='obj1'>obj1</div>
<div class='objeto' id='obj2'>obj2</div>
<div class='objeto' id='obj3'>obj3</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<div class='objeto'>obj1</div>
<div class='objeto'>obj2</div>
<div class='objeto'>obj3</div>
<script type='text/javascript'>
    var i;
    var objetos = document.getElementsByClassName('objeto');
    for (i = 0; i<objetos.length; i++){
         objetos[i].addEventListener('mouseover',function(){
                  borderObject(objetos[i]);
         }, false);
    };
    function borderObject(objetos){ objetos.style.border="4px solid red"; }
</script>

答案 2 :(得分:0)

定义for循环之外的悬停行为 -

let addListener = function(id) {document.getElementById(id).addEventListener('mouseover', function(){
                        borderObject(id);
                    }, false);
                }

var objetos = document.getElementsByClassName('objeto');
for (var i = 1; i < objetos.length + 1; i++){
     var id = 'obj'+i; 
     addListener(id)
};