jQuery过滤器帮助

时间:2009-12-18 20:41:28

标签: javascript jquery filter return-value

此代码有什么问题......

var objects = $(".validated").filter(function(){
                                   return $(this).attr("name") == 'name';
                             }).filter(function (){
                                   return $(this).val() == '';
                             });

它真的让我烦恼:(

2 个答案:

答案 0 :(得分:2)

var objects = $(".validated").filter(function() {
    var ele = $(this);
    return ele.attr("name") == 'name' || ele.val() == '';
});

答案 1 :(得分:0)

当函数返回false时,Filter将删除元素。所以当你遇到名字=“name”的元素和它是空的元素时,你希望它返回false。

var objects = $(".validated").filter(function(){
                                   // Will return false when name="name"
                                   return $(this).attr("name") != 'name';
                             }).filter(function (){
                                   // Will return false when the value is blank
                                   // Added trim to ensure that blank spaces
                                   // are interpreted as a blank value
                                   return $.trim($(this).val()) != '';
                             });

缩短版本将是:

var objects = $(".validated").filter(function(){
                  // Will return false when name="name" or blank value
                  return $(this).attr("name") != 'name' && $.trim($(this).val()) != '';
              });