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

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

最佳答案

您正在重新定义函数范围内的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

09-25 19:13