javascript - setAttribute 在 a 内使用 javascript 进行评估

标签 javascript evaluation setattribute

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

该元素是从类(事件)中提取的,并分配了一个变量。从不同的类 (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

关于javascript - setAttribute 在 a 内使用 javascript 进行评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17955238/

相关文章:

javascript - DOM 不显示动态添加的图像

javascript - 主干和 $el 元素

java - Java 中方法调用和参数之间的求值顺序

sql-server - Linux MS SQL Server 评估已过​​期,无法升级为开发人员

javascript - 如何使svg组中的所有元素改变颜色onclick(js)

javascript - 当 onfocus 设置选择大小时,Google Chrome 会崩溃

javascript - model.find 方法未从数据库返回必填字段

javascript - localForage 在 Chrome 中找到数据,在 Firefox 中找不到

来自流阅读器的 F# 懒惰评估?

javascript - setAttribute 和 htmlElement.attribute ='value' 的区别