jquery 数字比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7565574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery number compare
提问by fish man
I met a trouble to compare number in jquery. test code here:
我在 jquery 中比较数字时遇到了麻烦。测试代码在这里:
<script src="jquery.js"></script>
<script>
jQuery(document).ready(function(){
var val1 = $("#aaa").attr('title');
var val2 = $("#bbb").html();
if(val1>=val2){
$("#ccc").html(val1);
}else{
$("#ccc").html(val2);
}
});
</script>
<div id="aaa" title="1">aaa</div>
//set title=1 show 1, set title=2 show 111
<div id="bbb">111</div>
<div id="ccc"></div>
As code show, two number from html dom. now I set number in div#aaa[title]
, if set number one, it is right, and if set number 2, the result is wrong. Where is the problem? Thanks.
如代码所示,来自 html dom 的两个数字。现在我在 中设置数字div#aaa[title]
,如果设置为1,则正确,如果设置为2,则结果错误。问题出在哪儿?谢谢。
回答by Igor Dymov
You are comparing strings, convert them to int with parseInt(value, 10);
您正在比较字符串,将它们转换为 int parseInt(value, 10);
var val1 = parseInt($("#aaa").attr('title'), 10);
var val2 = parseInt($("#bbb").html(), 10);
回答by Samich
You need to compare int
values, not a strings
您需要比较int
值,而不是字符串
jQuery(document).ready(function(){
var val1 = parseInt($("#aaa").attr('title'));
var val2 = parseInt($("#bbb").html());
if(val1>=val2){
$("#ccc").html(val1);
}else{
$("#ccc").html(val2);
}
});