简体   繁体   English

用于计算的JavaScript函数不起作用?

[英]JavaScript function for calculating is not working?

this is my html input field 这是我的html输入字段

<input type="number" id="t1">
<br /> 
<button type="button" onclick="getvalue()">calculate</button>
<br />
<div id="l1">change<div>

this is my script 这是我的剧本

<script>
function getvalue() {
  var l = document.getElementById('l1');
  var c = document.getElementById('t1').value;
  var lc = c + 200;
  var tax =  2.1;
  var tot = lc * tax;
  l.innerHTML=tot;
}
</script>

and in text box i enter 10 so result is 441 this is the calculation 10+200 = 210 then 210*2.1 = 441 并在文本框中输入10,因此结果为441,这是计算10 + 200 = 210然后210 * 2.1 = 441

but in text box i enter 10 and click button i got 21420 但在文本框中,我输入10并单击按钮,我得到21420

the problem is var lc = c + 200; 问题是var lc = c + 200; this is not calculate correct here its work 10200 这不是正确的计算方法,其工作10200

and i try this method also var x = 200; 我也尝试这种方法var x = 200; var lc = c + x; this is also i got 10200 how can i fix this? 这也是我10200我该如何解决?

type of value in input number is string . input number中值的typestring

 var val = document.getElementById('t1').value ; console.log( typeof val ) ; 
 <input type="number" id="t1"> 

So you must convert to number like this: 因此,您必须像这样转换为数字:

var lc = Number(c) + 200 ;
//OR
var lc = parseInt(c) + 200 ;
//OR
var lc = parseFloat(c) + 200 ;

 function getvalue() { var l = document.getElementById('l1'); var c = document.getElementById('t1').value; var lc = Number(c) + 200; var tax = 2.1; var tot = lc * tax; l.innerHTML=tot; } 
 <input type="number" id="t1"> <br /> <button type="button" onclick="getvalue()">calculate</button> <br /> <div id="l1">change <div> 

Even though the type of input is number , actually the value is of type string. 即使输入的类型是number ,但实际上值的类型还是string。 That's why string concatenation is happening. 这就是字符串串联发生的原因。

You can check the type of value with typeof operator. 您可以使用typeof运算符检查值的类型。

To perform the intended arithmetic operation, you have to convert the value to number. 要执行预期的算术运算,您必须将值转换为数字。

Please Note: It is better to use textContent instead of innerHTML when dealing with text only content. 请注意:处理纯文本内容时,最好使用textContent而不是innerHTML

var c = Number(document.getElementById('t1').value);

 function getvalue() { var l = document.getElementById('l1'); var c = document.getElementById('t1').value; console.log(typeof(c)); //string var lc = Number(c) + 200; var tax = 2.1; var tot = lc * tax; l.textContent = tot; } 
 <input type="number" id="t1"> <br /> <button type="button" onclick="getvalue()">calculate</button> <br /> <div id="l1">change <div> 

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

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