繁体   English   中英

为什么这个javascript代码没有输出? 我错过了什么?

[英]Why is there no output with this javascript code? What am I missing?

这是我写的一些示例代码,因为我有一个更难的任务,但现在我什至无法让它工作。 只是想显示两个数字相加的输出,我错过了什么?

<!DOCTYPE html>
<html>
<head>
    <title>Sample</title>
    <script type="text/javascript">
        function Add() {
            var n1 = document.getElementById("numOne").value;
            var n2 = document.getElementById("numTwo").value;
            var total = n1 + n2;

            document.getElementById("output").innerHTML = total;
        }
    </script>
</head>
<body>
    <h1>Calc</h1><br />
    <form method="post" action="">
        NUM 1: <input type="number" name="numOne" id="numOne" /><br />

        NUM 2: <input type="number" name="numTwo" id="numTwo" /><br />

        <input type="button" value="Add" onclick="ADD()" /><br />

        Result: <label id="output"></label>
    </form>
</body>
</html>

引用时需要匹配函数名的大小写。 ADD()应该是Add() 请咨询您的开发者控制台以获取错误消息。

此外,如果您想对这两个数字求和,您需要先将它们从字符串中转换,这样您就不会执行连接。

    function Add() {
        var n1 = document.getElementById("numOne").value;
        var n2 = document.getElementById("numTwo").value;
        var total = parseInt(n1, 10) + parseInt(n2, 10);

        document.getElementById("output").innerHTML = total;
    }

在这里,我使用基数为10 parseInt()将数字字符串转换为数字。

ADD() => 更改为Add() (Javascript 区分大小写)

Number()函数将字符串转换为数字。 完美运行,运行并查看。 (如果你不放这个,你的输入是56 ,那么你的输出将是56 (字符串连接)而不是11

 <head> <title>Sample</title> <script type="text/javascript"> function Add() { var n1 = document.getElementById("numOne").value; var n2 = document.getElementById("numTwo").value; var total = Number(n1) + Number(n2); // Number() function document.getElementById("output").innerHTML = total; } </script> </head> <body> <h1>Calc</h1><br /> <form method="post" action=""> NUM 1: <input type="number" name="numOne" id="numOne" /><br /> NUM 2: <input type="number" name="numTwo" id="numTwo" /><br /> <input type="button" value="Add" onclick="Add()" /><br /> Result: <label id="output"></label> </form> </body>

函数名称区分大小写,您需要更改:

<input type="button" value="Add" onclick="ADD()" /><br />

对此:

<input type="button" value="Add" onclick="Add()" /><br />

暂无
暂无

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

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