关于Jquery .each函数的奇怪问题

时间:2013-11-21 22:48:12

标签: javascript jquery html

我的代码中有一个奇怪的问题

我有类似

的东西
var test, result;
$(".class td").each(function(){
     test = $(this).find('input').attr('size');
     if(test){
         result = test * 10;
     }
     console.log(result);
})

并非每个td都有输入字段,因此test可能是undefined。但是,在定义测试后,控制台将始终从test输出值。

例如:

   undefined (test = undefined)
   undefined (test = undefined)
   undefined (test = undefined)
   200 (test = 20)
   200 (test = undefined)
   200 (test = undefined)
   200 (test = undefined)

我不确定这里发生了什么。有人可以帮我吗?感谢。

2 个答案:

答案 0 :(得分:4)

在内部范围中定义result而不是将其保留在外部范围内,因为第一个结果具有值,您的进一步迭代仍然保留旧值,这就是您所看到的。

$(".class td").each(function(){
     var result , 
         test = $(this).find('input').attr('size');
     if(test){ //remove this check and you will see NaN for the iterations where test = undefined in your code
         result = test * 10;
     }
     console.log(result);
});

您还可以避免循环没有输入字段的td。

$(".class td:has(input)").each(...

$(".class td:has(input[size])").each(...

答案 1 :(得分:0)

您可以抓住选择器中的输入,并将每个项目的结果映射到数组:

var result = $('.class td input').map(function() {
  return $(this).attr('size') * 10;
}).toArray();