javascript - 否则将无法使用 'document.getElementById()'

标签 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);
    }
}

最佳答案

查看下面代码中突出显示的语法错误:

} 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;
    }
};

关于javascript - 否则将无法使用 'document.getElementById()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31042577/

相关文章:

javascript - 为什么 bool 值的解构可以在 JavaScript 中工作?

javascript - 日期和 Chrome

jquery - 如何更改 jQuery Accordion 的动画风格?

html - 仅在 IE 10 中应用的用于列表项的 CSS 填充

html - 3 列 div 布局不适合我

javascript - 使用打开和关闭按钮停止 Google Chrome 扩展。如何?

javascript - 如何在 react 中正确创建 cmd+K 键盘快捷键?

jquery - Knockout.js:来自oberservableArray的knockout-sortable css更新

javascript - Bootstrap-Tour RTL Popover 位置

html - 这是有效的 css