繁体   English   中英

JavaScript不会在函数中输出值

[英]JavaScript won't output value in function

嗨,我是Javascript的新手。 在下面的代码中,当我测试时,我没有看到任何输出。 谁能告诉我有什么问题?

    <script>
        function myFunction()
        {
            var x="";
            var score=document.myscore.score.value;

            if (score>30)
            {
                x="Expert";
            }
            else
            }
                x="Novice";
            }
            document.write(x);
        }
    </script>
</head>
<body>
    <form name="myscore">
        Score: <id="score"> <input type="number" name= "score">
        <input type="submit" onClick="myFunction()" value="submit">

    </form>


</body>

<script>
function myFunction()
{
var x="";
var        score=document.myscore.score.value;

if (score>30)
        {
            x="Expert";
        }
        else
        {
            x="Novice";
        }
        document.write(x);
    }
</script>
</head>
<body>
<form name="myscore">
Score: <id="score"> <input type="number" name= "score">
<input type="submit" onClick="myFunction()" value="submit">

</form>


</body>

这应该工作! 问题是{在else之后的方向。

一些东西:

  1. <id="score"> <input type="number" name= "score">可能不是您的意思。 也许你的意思是<input type="number" name="score" id="score">
  2. document.write是禁止的,请不要使用它。 它允许您“在此处和现在”修改文档,即加载时。 例如,使用document.body.innerHTML += x
  3. var score = document.getElementByID('score').value
  4. else子句后的括号

尝试这个:

  <script>
    function myFunction()
    {
        var x;
        var score=document.getElementById("in_score").value;

        if(score>30)
          x="Expert";
        else
          x="Novice";
        document.getElementById("score").value = x;
    }
  </script>
  <body>
    <form name="myscore">
     Score: <input id="score" type="number" name= "score">
     <input type="submit" id="in_score" onClick="myFunction()" value="submit">

    </form>


   </body>
   </html>

因此,代码中的主要错误是else语句的反向括号。 此外,要从输入获取/更改值,您需要使用getElementById(以选择元素)和.value语句来更改/获取它。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>enter code here
 <script>
        function myFunction()
        {
            var x="";
            var score=document.myscore.score.value;

            if (score>30)
            {
                x="Expert";
            }
            else
             {
                x="Novice";
            }
            document.write(x);
        }
    </script>
</head>
<body>
    <form name="myscore">
        Score: <id="score"> <input type="number" name= "score">
        <input type="submit" onClick="myFunction()" value="submit">

    </form>


</body>
</html>
  • 将输入类型从submit更改为button否则您将无法看到输出,因为表单将提交并重新加载页面。
  • 修复语法错误 <id =“score”> Change} to {under else condition
  • 将document.write更改为alertconsole.log

暂无
暂无

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

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