0

I'm using jquery to find the value of an attribute

var dataWidth = jQuery('#myContainer').attr('data-width'); 

I'm trying to check the dataWidth var is both a numeric value and is less than 320. If it's not then set a default value. Here is what I have at the moment.

if(parseInt(dataWidth) > 320) {
        var dataWidth = 320
}

Can anybody let me know what i'm doing wrong?

4

2 回答 2

0

parseInt()NaN如果传入的字符串无法正确转换为数字,将返回。与任何其他数字(甚至其自身)之间的任何相等/不相等比较都将返回 false。(并返回假。)NaNNaNNaN < 320NaN > 320

这就是为什么您还应该使用isNaN来检查 if dataWidthis NaN

var dataWidth = parseInt(jQuery('#myContainer').attr('data-width'));

if (isNaN(dataWidth) || dataWidth > 320) {
  dataWidth = 320;
}
于 2013-06-16T18:09:23.493 回答
0
if ( parseInt( $('#myContainer').data('width') ) > 320 ) {
    $('#myContainer').data('width', '320');
}
于 2013-06-16T18:04:26.960 回答