jQuery如何检查值不为null/空或NaN

3

我目前正在使用jQuery检查值是否为NaN,并希望将检查扩展到不为空或空字符串,但不确定如何实现,这里是我的代码;

<script type="text/javascript"> // ensure quantity textbox is numeric
$(document).ready(function () {
    $('[id$=txtQuantity]').change(function () {
        if(isNaN(this.value)) {
            alert("Please ensure the quantity specified is numeric");
            $(this).val("1");
        }
        else{
            $(this).val(this.value);
        }
    });
});


if(isNaN(this.value)) { 更改为 if(!this.value || isNaN(this.value)) { - Royi Namir
如果我猜想得没错的话,他可能希望写成if(!this.value || isNaN(this.value)),换句话说,如果为空或非数值。 - Ben Robinson
@BenRobinson 是的,已经编辑过了。 :-) - Royi Namir
2个回答

6
你可以更改以下内容:
if(isNaN(this.value)) 

To

if(!this.value || isNaN(this.value)) ...

但是你为什么不使用jQuery.isNumeric呢?因此:
if(!jQuery.isNumeric(this.value)) {
            alert("Please ensure the quantity specified is numeric");
            $(this).val("1");
        }
        else{
            $(this).val(this.value);
        }

4

你可以直接检查是否为空,如:

(myVar !== null)

要检查变量是否为空,你可以这样做:

(myVar !== '')

对于数字检查,可以使用isNaN()$.isNumeric(),但是$.isNumeric()返回的布尔值更加准确,请点击此处了解更多。

(isNaN(myVar))(!$.isNumeric(myVar))

所有的内容综合在一起:

if ( (myVar !== null) || (myVar !== '') || (!$.isNumeric(myVar)) ){ ... }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接