使用javascript的非常基本的程序中的错误

Error in a very basic program using javascript

本文关键字:程序 错误 javascript 非常 使用      更新时间:2023-09-26

如果person不是null,则输出第一个条件,否则显示一个警告框。但如果输入null它不会执行第二个条件 - 它继续使用第一个条件。

<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
    var person = prompt("Please enter your name");
    if (person != null) {
        document.getElementById("demo").innerHTML =
        "Hello " + person + "! How are you today?";
    }
    else if (person == null ){
            alert("How dare you ?>");
    }
}
</script>
</body>
</html>

问题很可能是你实际上并没有输入 null,而你认为是。

null是特殊的:它是一个表示缺少值的特殊值。不要与"null"混淆,包含单词"null"或"的字符串,空字符串。

prompt()仅在取消时返回null。当您"输入 null"时,您可能会以"null"或"结束,具体取决于您是否在框中键入任何内容。

看:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/null

所以你的固定代码将是:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
    var person = prompt("Please enter your name");
    if (person != "") {
        document.getElementById("demo").innerHTML =
        "Hello " + person + "! How are you today?";
    } else {
        alert("How dare you ?>");
    }
}
</script>
</body>
</html>

myFunction() 没有定义按钮何时分配事件处理程序,因此将脚本放在 head 标签中。为了检查字符串值需要输入"而不是null

我修改了你的代码,试试这个它会起作用...它对我来说工作正常。

<!DOCTYPE html>
    <html>
    <head>
         <script>
    function myFunction() {
        var person = prompt("Please enter your name");
        if (person != "") {
            document.getElementById("demo").innerHTML =
            "Hello " + person + "! How are you today?";
    }
        else {
                alert("How dare you ?>");
    }
    }
    </script>
    </head>
    <body>
    <p>Click the button to demonstrate the prompt box.</p>
    <button onclick="myFunction()">Try it</button>
    <p id="demo"></p>
    </body>
    </html>