【问题标题】:setAttribute with javascript inside a for evaluation用于评估的 setAttribute 和 javascript
【发布时间】:2013-07-30 19:02:21
【问题描述】:

我正在尝试为元素设置属性。

元素从一个类(活动)中提取并分配一个变量。从不同的类 (topArrow) 中提取相同的元素并分配一个变量。

当比较两个变量以运行 if 语句时,评估结果不一样...???

console.log 看看发生了什么,我明白了:

HTMLCollection[img.active images/a.../top.png]
HTMLCollection[]

在没有 topArrow 类的元素上,我得到了这个:

HTMLCollection[img.active images/a...left.png]
HTMLCollection[img.topArrow images/a.../top.png]

    var arrow = 0;

var topArrow = document.getElementsByClassName("topArrow");
var menuText = document.getElementsByClassName("menuText");
var rightArrow = document.getElementsByClassName("rightArrow");
var bottomArrow = document.getElementsByClassName("bottomArrow");
var leftArrow = document.getElementsByClassName("leftArrow");

//assign navButtons to var buttons (creates array)
var buttons = document.getElementsByClassName("navButton");

//for each instance of buttons, assign class "active" onmouseover
for(var i = 0; i < buttons.length; ++i){
    buttons[i].onmouseover = function() {
        this.className = "active";
        var arrow = document.getElementsByClassName("active");
        console.log(arrow);
        console.log(topArrow);
        changeImages();
    }
}

//for each instance of buttons, remove class "active" onmouseout
for(var i = 0; i < buttons.length; ++i){
    buttons[i].onmouseout = function () {
        this.className = "";
    };
}

function changeImages(){
    if ( arrow == topArrow ) {
        this.setAttribute("src", "images/arrows/top_o.png");
        console.log("arrow should change");
    } else {
        console.log("arrow should not change");
    }
}

【问题讨论】:

    标签: javascript evaluation setattribute


    【解决方案1】:

    您正在函数范围内重新定义arrow,这掩盖了全局定义。

    var arrow = 0;//global
    
    var arrow = document.getElementsByClassName("active");// overshadowing assignment
    

    即使你修复是删除var,因此 -

    arrow = document.getElementsByClassName("active");// var removed
    

    当你使用document.getElementByClassName 时,你得到一个HTMLCollection,而不是那个元素,即使有一个匹配。使用 == 匹配的数组不会按照您想要的方式运行。

    修复这种使用 -

    if(arrow[0] == toparrow[0])//assuming you have only one element with class 'active' and 'toparrow' in dom
    

    【讨论】:

    • 谢谢。所以我必须深入到元素的节点......或者我怎样才能实现一个简单的“如果有这个类那么......否则......”?
    • 看起来更好......但不幸的是我得到“TypeError:箭头为空”。对于 console.log(arrow);我看到:HTMLCollection[img#topArrow.active images/a.../top.png],比以前更好。 console.log(topArrow);现在返回实际元素:“”。不确定从这里去哪里
    • 是否可以评估元素的属性?
    • 你能不能也发布 HTML,会有很大帮助。
    • 您正在重新定义第 54 行中的箭头 var arrow = document.getElementsByClassName("active"); 只需使用 arrow = document.getElementsByClassName("active"); 删除 var
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多