用javascript交换img标签

用javascript交换img标签

我正在尝试制作一个hang子手游戏,如果选择了错误的字母,它将在a子手模型中添加一个身体部位。我希望它在显示左臂后立即显示,在下一个字母条目中显示右臂。但是它们都出现在第一个错误的条目上

//JavaScript document
var answer = ['h', 'a', 'n', 'g', 'm', 'a', 'n'];
var wrong= ['b' ,'c' ,'d', 'e' ,'f' ,'i' ,'j' ,'k' ,'l','o' ,'p', 'q', 'r', 's' ,'t', 'u', 'v' ,'w', 'x' ,'y' ,'z'];
var letters = /^[a-zA-Z]*$/;
var answerLetter = document.getElementsByClassName("answer_char");
var letterpool= ['a ' ,'b ' ,'c ' ,'d ', 'e ' ,'f' ,'g ' ,'h ' ,'i ' ,'j ' ,'k ' ,'l ', 'm ' ,'n ' ,'o ' ,'p ', 'q ', 'r ', 's ' ,'t ', 'u ', 'v ' ,'w ', 'x ' ,'y ' ,'z '];
var leftarm = false

onload = init;
function init(){
    updateDisplay()

    document.getElementById("guess_button").onclick = function enter() {
        var userGuess = document.getElementById("guess_text").value;
        // This uses String.prototype.match() used too see if its both a letter and a single entry
        if(userGuess.match(letters) && userGuess.length === 1) {
            for (var i = 0; i < answer.length; i++) {
                if (userGuess === answer[i])
                    // answer[i] correlates to answerLetter[i].
                    answerLetter[i].innerHTML = userGuess;
            }
            if(userGuess.match(letters) && userGuess.length === 1) {
                for (var i = 0; i < wrong.length; i++) {
                    if (userGuess === wrong[i])
                        document.getElementsByTagName("img")[1].src="img/leftarm_on.png";
                    leftarm = true;
                }
                if(leftarm= true){
                    document.getElementsByTagName("img")[3].src="img/rightarm_on.png";
                }

            }
        }else {
            window.alert('please enter one letter, numbers need not apply .');
        }
    }

}

最佳答案

        if (userGuess === wrong[i])
       document.getElementsByTagName("img")[1].src="img/leftarm_on.png";
       leftarm = true;
       }
       if(leftarm= true){
           document.getElementsByTagName("img")[3].src="img/rightarm_on.png";
       }



您正在此处依次测试条件-当您在第一个中设置leftarm时,在第二个中已经设置为true。顺便说一句,您不是使用==比较,而是使用=分配;实际上,根本不需要进行这种比较。它应该是

if (userGuess === wrong[i]) {
    if (!leftarm) {
        document.getElementsByTagName("img")[1].src="img/leftarm_on.png";
        leftarm = true;
    } else if (leftarm) {
        document.getElementsByTagName("img")[3].src="img/rightarm_on.png";
    }
}

关于javascript - 用javascript交换img标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29358716/

10-09 02:15