1

我将如何在不使用 .each() 且仅使用 JQuery 选择器的情况下编写这两种方法?

var xxxx = 0;
$('.clonedInput').each(function(index) {
    if($(this).children().filter(':checked').length == 2)
    xxxx++;
});


var num_normal_foods = 0;
$('[id^="amount_"]').each(function(index) {
    if($(this).val() == '30.00')
    num_normal_foods++;
});
4

2 回答 2

3

jQuery 选择有一个 .length 属性:

var len = $('.clonedInput :checked').length;
var len2 = $('[id^="amount_"][value="30.00"]').length;

第一个查询返回任何 .clonedInput 类的所有已检查子项,然后对它们进行计数。

第二个查询查找所有以amount_ 开头并且值为“30.00”的ID。(属性查询可以像 [][] 那样链接)

编辑: 满足@Blazemonger

要获取任何类型元素的值(值适用于某些元素),请使用以下命令:

var len2 = $('[id^="amount_"]').filter(function() {
  return $(this).val() == "30.00";
}).length;

双重编辑,因为我没用

var len = $('.clonedInput').filter(function(){
   return $(this).children(':checked').length == 2;
}).length;
于 2012-07-19T13:30:00.163 回答
3

让我们一步一步来。

你开始:

var xxxx = 0;
$('.clonedInput').each(function(index) {
    if($(this).children().filter(':checked').length == 2)
    xxxx++;
});

对我来说,这看起来就像你只是在尝试filter一组.clonedInput元素并找出有多少匹配过滤器:

var xxxx;
function hasTwoCheckedChildren(i) {
    return $(this).children(':checked').length == 2;
}
xxxx = $('.clonedInput').filter(hasTwoCheckedChildren).length;

其次是:

var num_normal_foods = 0;
$('[id^="amount_"]').each(function(index) {
    if($(this).val() == '30.00')
    num_normal_foods++;
});

同样,这对我来说看起来像是一个过滤功能:

var num_normal_foods;
function valueIsThirty(i) {
    return +$(this).val() === 30;
}
num_normal_foods = $('[id^="amount_"]').filter(valueIsThirty).length;

最后,重要的是代码执行您想要执行的操作。如果您编写的代码.each符合您的要求,则无需更改它。无论如何在幕后filter使用。each

于 2012-07-19T13:35:41.800 回答