【问题标题】:Assigning onmouse events with a loop to a div array - Javascript将带有循环的鼠标事件分配给 div 数组 - Javascript
【发布时间】:2014-03-31 07:09:32
【问题描述】:

我正在尝试将 onmouseover - onmouseout 事件分配给带有循环的 div 数组。

我也通过循环创建了 div,使用函数参数 createDivs(x)x 是 div 的数量和一堆 this.property 来分配样式。

一切都按预期工作,但通过带有divArray.Length 对象的循环分配鼠标事件。

脚本如下:

制作 div:

containers : {

    create : function(containerCount){
        var cArray = [this.c1Color,this.c2Color,this.c3Color];
        var aCounter = 0;
        divArray = [];
        for (var i = 1; i <= containerCount; i++){
            var c = document.createElement("div");
            c.id = ("container"+i);
            c.style.width = "100%";
            c.style.height = (this.height) + "px";
            c.style.backgroundColor = (cArray[aCounter]);
            aCounter++;
            document.body.appendChild(c);
            divArray.push(c);

            }

        }

},

分配事件:

events : {

    on : function () {

        var z = 1;

        for (var i = 0; i < divArray.length; i++){

            var cont = ("container" + z);

            document.getElementById(divArray[i].id).onmouseover = function(){
                gala.animate.openAnimation(cont);
            }

            document.getElementById(divArray[i].id).onmouseout = function(){
                gala.animate.shrinkAnimation(cont);
            }

            console.log(cont);
            z++;

        }

    }

控制台显示数组按预期按 div 数排序,cont 变量++ 增加以分配 id。但是最后,事件侦听器仅应用于数组的最后一个元素。

顺便说一句,cont 变量只是传递动画方法的参数的占位符,因此它知道要为哪个 div 设置动画,这意味着 animat.openAnimation(cont) cont = div 名称。

【问题讨论】:

标签: javascript arrays dom-events


【解决方案1】:

看起来您需要一个新范围来将cont 变量的值保持在事件处理程序中。我替换了 cont 变量,因为它似乎并不需要

events : {

    on : function () {

        for (var j = 0; j < divArray.length; j++){

            (function(i) {

                divArray[i].onmouseover = function(){
                    gala.animate.openAnimation("container" + (i+1));
                }

                divArray[i].onmouseout = function(){
                    gala.animate.shrinkAnimation("container" + (i+1));
                }

            })(j);

        }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 2012-05-27
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多