Javascript - 平均计算

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26831438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:33:55  来源:igfitidea点击:

Javascript - Average calculation

javascriptaverage

提问by Eric

Hi I am trying to write a simple calculation that will average the two numbers entered by user input and then click the average button to get the average of the two. MY problem is that it does not produce an answer. Here is the code

嗨,我正在尝试编写一个简单的计算,该计算将对用户输入的两个数字求平均值,然后单击平均值按钮以获得两者的平均值。我的问题是它不会产生答案。这是代码

<html>
<body>
<input type="text" id="one">
<input type="text" id="two">

<input type ="button" onclick="average()"value="average">
<input type="text" id ="avg">
<script type"text/javascript">>
function average(){
    var a=parseInt(document.getElementById("one".value);
    var b=parseInt(document.getElementById("two".value);
    var afinal=((a+b)/2);
        document.getElementById('avg').value=afinal;
    }
</script>   
    </body>
</html>

回答by skobaljic

Typo fix (missing bracket for getElementById):

错别字修复(缺少括号getElementById):

var a=parseInt(document.getElementById("one").value);
var b=parseInt(document.getElementById("two").value);

and another typo:

和另一个错字:

<script type"text/javascript">>

should be:

应该:

<script type"text/javascript">

so, the final code is:

所以,最终的代码是:

<html>
<body>
    <input type="text" id="one">
    <input type="text" id="two">

    <input type ="button" onclick="average()"value="average">
    <input type="text" id ="avg">
    <script type"text/javascript">
    function average(){
        var a=parseInt(document.getElementById("one").value);
        var b=parseInt(document.getElementById("two").value);
        var afinal=((a+b)/2);
            document.getElementById('avg').value=afinal;
        }
    </script>   
    </body>
</html>

回答by AbhishekTaneja

It is just a typo fix,

这只是一个错字修复,

instead of

代替

var a=parseInt(document.getElementById("one".value);
var b=parseInt(document.getElementById("two".value); 

the code becomes,

代码变成,

var a=parseInt(document.getElementById("one").value);
var b=parseInt(document.getElementById("two").value);

回答by Alex Weinstein

Instead of writing the old-school document.getElementById(), consider using an industry-standard, broadly adopted jQuery library, specifically its method called $.

与其编写老式的 document.getElementById(),不如考虑使用行业标准、广泛采用的 jQuery 库,特别是其名为 $ 的方法。

There, you'll be able to use a CSS selector to get to an element that you want. It's extremely powerful, I recommend learning it.

在那里,您将能够使用 CSS 选择器来获取您想要的元素。它非常强大,我建议学习它。

var a = $("#one").val();