每个jQuery:如果元素在元素中

时间:2018-03-22 11:15:33

标签: javascript jquery if-statement each

为什么我有几个div,我想根据内容给出不同的高度。他总是从第一个条件中获得高度。



$('.box-site-promo').each(function(index) {

  console.log($(this));

  if ($(this).find('.box-site-tags')) {
    heightBox = 200;
    console.log(index + " " + heightBox);
  } else if ($(this).find('.box-site-authors')) {
    heightBox = 100;
    console.log(index + " " + heightBox);
  } else {
    heightBox = 300;
    console.log(index + " " + heightBox);
  }

  $(this).height(heightBox);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="box-site-promo"> A
  <div class="box-site-tags">some tags</div>
</div>
<div class="box-site-promo"> B
  <div class="box-site-authors">authors</div>
</div>
<div class="box-site-promo"> C
  <div class="box-site-tags">some tags</div>
</div>
<div class="box-site-promo"> D </div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您的第一个条件始终为true,因为$.fn.find会返回jQuery个对象,无论是否找到任何匹配元素,该对象始终会计算为true。< / p>

要检查对象是否包含任何元素,您可以检查其length属性:

if ($(this).find('.box-site-tags').length > 0)

<强>段:

/* ----- JavaScript ----- */
$(".box-site-promo").each(function(index) {
  var $this = $(this), heightBox = 300;
  
  if ($this.find(".box-site-tags").length > 0) {
    heightBox = 200;
  } else if ($this.find(".box-site-authors").length > 0) {
    heightBox = 100;
  }
  
  console.log(index + " " + heightBox);
  $this.height(heightBox);
});
<!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="box-site-promo"> A
  <div class="box-site-tags">some tags</div>
</div>
<div class="box-site-promo"> B
  <div class="box-site-authors">authors</div>
</div>
<div class="box-site-promo"> C
  <div class="box-site-tags">some tags</div>
</div>
<div class="box-site-promo"> D </div>

答案 1 :(得分:0)

使用length知道div是否有后代。正如在文档中所说,find返回jQuery集合。检查一下这个片段。此致

$('.box-site-promo').each(function(index) {

  //console.log($(this));

  if ($(this).find('.box-site-tags').length > 0) {
    heightBox = 200;
    console.log(index + " " + heightBox);
  } else if ($(this).find('.box-site-authors').length > 0) {
    heightBox = 100;
    console.log(index + " " + heightBox);
  } else {
    heightBox = 300;
    console.log(index + " " + heightBox);
  }

  $(this).height(heightBox);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="box-site-promo"> A
  <div class="box-site-tags">some tags</div>
</div>
<div class="box-site-promo"> B
  <div class="box-site-authors">authors</div>
</div>
<div class="box-site-promo"> C
  <div class="box-site-tags">some tags</div>
</div>
<div class="box-site-promo"> D </div>