这是我的html输入字段
<input type="number" id="t1">
<br />
<button type="button" onclick="getvalue()">calculate</button>
<br />
<div id="l1">change<div>
Run Code Online (Sandbox Code Playgroud)
这是我的剧本
<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>
Run Code Online (Sandbox Code Playgroud)
并在文本框中输入10,因此结果为441,这是计算10 + 200 = 210然后210*2.1 = 441
但是在文本框中我输入10并单击按钮我得到了21420
问题是 var lc = c + 200;这里计算不正确10200
我也尝试这种方法 var x = 200; var lc = c + x;这也是我得到10200我该如何解决这个问题?
type有价值的input number是string.
var val = document.getElementById('t1').value ;
console.log( typeof val ) ;Run Code Online (Sandbox Code Playgroud)
<input type="number" id="t1">Run Code Online (Sandbox Code Playgroud)
所以你必须转换为这样的数字:
var lc = Number(c) + 200 ;
//OR
var lc = parseInt(c) + 200 ;
//OR
var lc = parseFloat(c) + 200 ;
Run Code Online (Sandbox Code Playgroud)
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;
}Run Code Online (Sandbox Code Playgroud)
<input type="number" id="t1">
<br />
<button type="button" onclick="getvalue()">calculate</button>
<br />
<div id="l1">change <div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
248 次 |
| 最近记录: |