rba*_*all 87 javascript jquery casting
我有一个简单的html块,如:
<span id="replies">8</span>
Run Code Online (Sandbox Code Playgroud)
使用jquery我试图在值(8)中添加1.
var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);
Run Code Online (Sandbox Code Playgroud)
发生的事情是它出现如下:
81
然后
811
不是9,这将是正确的答案.我究竟做错了什么?
Dio*_*ane 185
parseInt()将强制它为integer类型,如果无法执行转换,则为NaN(不是数字).
var currentValue = parseInt($("#replies").text(),10);
Run Code Online (Sandbox Code Playgroud)
第二个参数(基数)确保将其解析为十进制数.
Jon*_*n P 29
Parse int是你应该在这里使用的工具,但是像任何工具一样,它应该被正确使用.使用parseInt时,应始终使用radix参数以确保使用正确的base
var currentValue = parseInt($("#replies").text(),10);
Run Code Online (Sandbox Code Playgroud)
Chu*_*uck 25
整数被转换为字符串而不是反之亦然.你要:
var newValue = parseInt(currentValue) + 1
Run Code Online (Sandbox Code Playgroud)
Gar*_*Nel 10
在IE中,parseInt对我不起作用.所以我只是在你想要的变量上使用+作为整数.
var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);
Run Code Online (Sandbox Code Playgroud)
关于 .js 的八进制误解 - 我刚刚使用了这个......
parseInt(parseFloat(nv))
Run Code Online (Sandbox Code Playgroud)
在使用前导零进行测试后,每次都会以正确的表示形式返回。
希望这可以帮助。