2

我有这段代码,它正在从文本框中读取值,我认为在尝试 parseInt() 之前检查 '' 是安全的,但显然不是。

我收到错误消息:

未捕获的类型错误:无法调用未定义的方法“toLowerCase”

使用此代码:

            var total = 0;
            $.each('.reg-input', function () {
                if ($(this).val() == '') {
                }
                else {
                    total += parseInt($(this).val());  //this line throwing error
                }                    
            });
            if (total == 0) {
                $('.RegisterContainer').hide();                    
            }
4

4 回答 4

7

'.reg-input'是一个字符串,this在这种情况下也将是一个字符串,而不是一个 dom 元素。试试这个:

$('.reg-input').each(function(){...
于 2012-09-26T19:34:57.460 回答
4

您收到奇怪错误的原因是您$.each使用字符串而不是集合调用。

字符串是一个对象,所以它仍然是一个集合,但集合中的项目是字符串类的属性和方法(并且toLowerCase是其中之一)。

要遍历使用选择器找到的元素,请使用each方法而不是$.each方法

$('.reg-input').each(function(){
  ..
});

现在this循环内部将是一个元素,而不是字符串类的成员,因此您可以使用它$(this).val()来获取值。

于 2012-09-26T19:39:04.040 回答
1

我有完全相同的问题,我通过分配$(this).val()给一个变量然后将变量解析为一个整数来解决它。因此,正确的解决方法是:

var total = 0;
        $.each('.reg-input', function () {
            if ($(this).val() == '') {
            }
            else {
                $this_val = $(this).val();
                total += parseInt($this_val);  //this line throwing error
            }                    
        });
        if (total == 0) {
            $('.RegisterContainer').hide();                    
        }
于 2014-03-25T22:18:54.647 回答
-1

if ($(this).val() == "") 检查该值是否是未定义的字符串“”。
您可以像这样使用 typeof 运算符 if(typeof $(this).val() == 'undefined')

于 2012-09-26T19:37:45.943 回答