简体   繁体   English

为什么这段代码的其他部分不运行?

[英]Why doesn't the else part of this code run?

I don't know if I am missing something but there is something wrong with this code. 我不知道我是否缺少某些内容,但是这段代码有问题。 When I leave the input area blank the else part should run, but it does not. 当我将输入区域留为空白时,else部分应该运行,但是不会运行。 Can someone explain me why? 有人可以解释我为什么吗?

<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>

<p> Put your name and see what happens. </p>

<input id="nameinput">
<button onclick="myFunction()">Click To See Your Name</button>
<p id="namedemo"></p>

<script type="text/javascript">

   function myFunction() {
    if (document.getElementById("nameinput") != "") {
        var u;
        u = document.getElementById("nameinput").value;
        document.getElementById("namedemo").innerHTML = "Your name is " + u;
    }

    else {
        alert("Please fill required field");
    }
}

</script>
 </body>
 </html>

You are missing the .value in your statement, It should be 您在语句中缺少.value ,应该是

if(document.getElementById("nameinput").value != ""){

Here is a working DEMO : https://jsfiddle.net/ku7ubhnL/ 这是一个有效的DEMO: https : //jsfiddle.net/ku7ubhnL/

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM