簡體   English   中英

setAttribute中帶有javascript以進行評估

[英]setAttribute with javascript inside a for evaluation

我正在嘗試為元素設置屬性。

從類(活動)中提取元素並為其分配變量。 相同的元素從另一個類(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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM