繁体   English   中英

使用输入和跨度字段进行JavaScript计算

[英]Javascript calculation using input and span fields

<input type="number" name="quantity" id="quantity">
<span id="price">4000</span>

<input type="text" value="" id="total" readonly>
<input type="button" value="calculate Total Price" onClick="calculate()">

我需要上面字段name="quantity"id="price" ,并使用javascript函数进行计算,并仅在单击“计算”按钮时才将其显示在字段id="total" 我尝试了以下javascript函数,但结果显示为NaN

function calculate(tot) {
        var quan = document.getElementsByName('quantity').value;
        var pri = document.getElementById('price');
        var pr = parseInt(pri);
        var tot = quan * pr;
        document.getElementById("total").value = tot;
}

每当您看到一个以复数形式表示的方法(例如getElementsByName它都会获取多个元素,或者我们称之为nodeList,并且即使只有一个匹配元素,您仍然会得到一个nodeList,而nodeList没有值,则可以访问nodeList像一个数组,并获得列表中的第一个元素,例如:

var quan = document.getElementsByName('quantity')[0].value;

另外, getElementById获取一个元素,而不是一个数字,您必须获取innerHTML

var pri = document.getElementById('price').innerHTML;

并记住parseInt的基数

parseInt(pri, 10)

并不是说您乘法时确实需要解析它

小提琴

您将需要一个for循环并遍历每个单独的值并将其放入一个值中。 像这样:

for(i=0; i<quan.length; i++) {

 var total+= quan[i];
}

暂无
暂无

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

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