过滤类名以生成jquery数组

时间:2012-07-28 03:04:47

标签: jquery jquery-selectors

我需要从类名创建没有类名'hidden'的数组:

<div id="part2">
<div class="address hidden">address</div>
<div class="floors">floors</div>
<div class="postcode"> </div>
<div class="city hidden"> </div>
</div>

我可以翻看div并按如下方式制作数组但我只需要隐藏没有类的div - 在这种情况下只有'floor'和'postcode'。

 var list_div_class = function() {
  var myarray = [];
  $('#part2').children().each(
      function(index) {
  var myclass = $(this).attr("class");
   myarray[index] = myclass;
        });
     return myarray;
    }

var arr_divs = list_div_class();
  alert (arr_divs);  // there is hidden listed but it's ok 

4 个答案:

答案 0 :(得分:2)

您可以使用一行中的选择器执行此操作:

var arr_divs = $('#part2 div:not(".hidden")'); //this will be the array of divs without the class .hidden 

答案 1 :(得分:0)

试试这个......这是一个有用的小提琴链接http://jsfiddle.net/n3Xjr/

var list_div_class = function() {
  var myarray = [];

  $('#part2').children().not('.hidden').each(function(index) {
    myarray[index] = $(this).attr("class");
  });

  return myarray;
}

var arr_divs = list_div_class();
alert(arr_divs);​

答案 2 :(得分:0)

像这样:

$(':not(.hidden)').each { ... }

答案 3 :(得分:0)

您也可以使用.map()

var arr = [];
arr = $('#part2').children().not('.hidden').map(function(i,e) {
    return $(e).attr('class');
}).get().join(', ');

结果:

floors, postcode

参考 LIVE DEMO