1

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

该元素从一个类(活动)中提取并分配一个变量。从不同的类 (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");
    }
}
4

1 回答 1

1

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

var arrow = 0;//global

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

即使您修复正在删除var,因此 -

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

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

要修复该使用 -

if(arrow[0] == toparrow[0])//assuming you have only one element with class 'active' and 'toparrow' in dom
于 2013-07-30T19:40:23.060 回答