gpt4 book ai didi

Javascript:为什么将数字视为字符串?

转载 作者:行者123 更新时间:2023-11-30 10:10:54 25 4
gpt4 key购买 nike

我想弄清楚为什么输入文本框中的数字被视为字符串。此处的简短脚本一直到我在第二个文本框中输入数字为止。第二个文本框中的值作为字符串附加到最终值,而不是作为数字添加。我尝试使用 parseInt() 但在那种情况下我的结果是 NaN。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

var extras_fee = 0;

function validate_extra1(){
var extra1_value = document.getElementById('extra1').value;
var extra2_value = document.getElementById('extra2').value;
var extra1_radiovalue = $('input[name=radio_extra1]:checked').val();
if (extra1_value.length > 0 && extra1_radiovalue == 2000)
{extras_fee = 2000;}
if (extra1_value.length > 0 && extra1_radiovalue == 4000)
{extras_fee = 4000;}
if (extra1_value.length == 0)
{extras_fee = 0;}
extras_fee = extras_fee + extra2_value;
document.getElementById('fee_container').innerHTML = extras_fee;
}
$(function(){
$(document).on('click', '#continue_extras', function(){
$("<div class='st'><b>Some title.</b></div>" +
"<div class='infwin'>Some text </div> " +
"<div>input some text here <input type='text' name='fname' id='extra1' onkeyup='validate_extra1()'>" +
"<input type='radio' name='radio_extra1' value='2000' onclick='validate_extra1()'>2000" +
"<input type='radio' name='radio_extra1' value='4000' onclick='validate_extra1()'>4000</div>" +
"<div class='infwin'>more text here</div> " +
"<div>input some numerical values here <input type='text' name='fname' id='extra2' placeholder='minimum 1000' onkeyup='validate_extra1()'> text</div>" +
"<div id='fee_container'></div>" +
"<div class='button' id='continue_post'>Submit >>></div> " +
"<div class='miclear'></div><br />").appendTo('#extras_container');
$('#continue_extras').hide();
});
});

</script>
</head>
<body>
<div id='continue_extras'>click</div>
<div id='extras_container'></div>
</body>
</html>​

最佳答案

您必须在添加之前验证 extra2_value

 var extra2_value = parseInt(document.getElementById('extra2').value);
extra2_value = extra2_value?extra2_value:0;

JsFiddle

关于Javascript:为什么将数字视为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26774515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com