.each以js返回值

时间:2016-12-22 01:21:07

标签: javascript jquery arrays loops

假设我有4个div元素:

<div class="example"></div> //empty
<div class="example"></div> //empty
<div class="example">hi</div> //has content
<div class="example"></div> //empty

然后使用.each,我想分配0(空)或1(有内容)的值:

var container = {}; 

container['status'] = $('div.example').each(function(){                 
         var inside = $(this).html();

         //Check for empty
         if (typeof inside == 'undefined' || inside == '' || inside == '<br>') {                        
             var warning = 0;

         }else{
             var warning = 1;

         }  
         return warning;

       });  

console.log(container);

在这种情况下,我想得到&#34; 0,0,1,0&#34;作为返回值。我该怎么做?

3 个答案:

答案 0 :(得分:2)

使用$.map()返回值数组

var container = {}; 

container["status"] = $.map($('div.example'), function(el) {  
                        return !el.textContent.trim().length || $(el).is(":empty") 
                               ? 0 : 1
                      });

答案 1 :(得分:1)

使用map功能 - 请参阅下面的演示:

var container = {};

container['status'] = $('div.example').map(function() {
  var inside = $(this).html();
  //Check for empty
  if (typeof inside == 'undefined' || inside == '' || inside == '<br>') {
    var warning = 0;
  } else {
    var warning = 1;
  }
  return warning;
}).get();

console.log(container);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example"></div>
<div class="example"></div>
<div class="example">hi</div>
<div class="example"></div>

答案 2 :(得分:1)

container['status'] = $(selector).each(YourFunc)

使用map代替每个,然后调用join加入元素

container['status'] = $(selector).map(YourFunc).get().join()

适用于Jquery 1.10.2