否则不能使用'document.getElementById()'

时间:2015-06-25 06:16:17

标签: javascript jquery html

所以我试图让else语句看起来像if,我只能让它在'alert()'上工作。

<nav></nav>
<img src="img/lion-white.svg" alt="logo" width="300px" />
<h1 id="intro" class="animated fadeInLeftBig">How many fingers am I holding up?</h1>
<input id="answer" type="value" placeholder="how many?"/><br/>
<button id="myButton">Submit</button>
<h1 id="right"></h1>
<h1 id="wrong"></h1>

JS代码:

document.getElementById("myButton").onclick=function() {
    var x = Math.random();

    x = 6*x;
    x = Math.floor(x);

    if (x==document.getElementById("answer").value) {
        document.getElementById("right").innerHTML="<h1>YOU'RE GOOD!</h1><h2>Thanks for playing!</h2>";
    } else {
        document.getElementById("wrong").innerHTML="<h1>That's wrong! My number was</h1> "+x);
    }
}

2 个答案:

答案 0 :(得分:2)

请参阅以下代码中突出显示的 SYNTAX ERROR

} else {
    document.getElementById("wrong").innerHTML = "<h1>That's wrong! My number was</h1> " + x);
    //                                                                                     ^^
}

检查代码没有错误:

document.getElementById("myButton").onclick = function() {

    var x = Math.random();
    x *= 6;
    x = Math.floor(x);

    if (x === parseInt(document.getElementById("answer").value, 10)) {
        //  ^ ^^^^^^^^^                                         ^^
        // parseInt will convert the string value in the integer and can be compared with the integer x

        document.getElementById("right").innerHTML = "<h1>YOU'RE GOOD!</h1><h2>Thanks for playing!</h2>";
    } else {
        document.getElementById("wrong").innerHTML = "<h1>That's wrong! My number was</h1> " + x;
    }
};

答案 1 :(得分:0)

您遇到语法错误(您有&#39; &#39;在行尾你不需要的东西)

document.getElementById("wrong").innerHTML="<h1>That's wrong! My number was</h1> "+x);

您需要修复

document.getElementById("wrong").innerHTML="<h1>That's wrong! My number was</h1> "+x;"

下次您应该使用Web开发人员工具(F12,firebug等),这样您就会看到控制台错误。