检查div是否有里面的图像,然后做一些事情

时间:2015-12-08 05:21:19

标签: jquery addclass

如果有<

我想将addClass添加到之前的div.local_text IMG> div.local_logo里面的标签

<div>
    <div class="local_text"></div>
    <div class="local_logo">
        <a href="#"></a>
    </div>
</div>

到目前为止,这不起作用,正在为所有div.local_text添加类,但仅添加前一个。

if (jQuery(".local_logo:has(img)")) {
    jQuery(".local_logo").prev(".local_text").addClass("half");
};

3 个答案:

答案 0 :(得分:2)

我建议:

// cache the <div clas="local_text"> elements:
var text = jQuery('.local_text');

// use toggleClass() with a class-name and switch,
// the class-name will be applied to the relevant elements
// if the switch returns a truthy value (0 is falsey):
text.toggleClass('half', text.next('div.local_logo').find('img').length);

请注意,如果下一个<div>包含<img>元素,则问题标题表示您要添加一个类,而问题中的代码包含<a>元素。

如果某处出现错误,请根据需要在find()内调整选择器。

参考文献:

答案 1 :(得分:2)

使用:has()选择器

  

选择包含至少一个与指定选择器匹配的元素的元素。

jQuery(".local_logo:has(img)") // Select all the classes `.local_logo` having img as descendent
    .prev(".local_text").addClass("half");

&#13;
&#13;
jQuery(".local_logo:has(img)").prev(".local_text").addClass("half");
&#13;
.half {
  background: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div class="local_text">First</div>
  <div class="local_logo">
    <img src="" alt="">
  </div>
</div>
<div>
  <div class="local_text">Second</div>
  <div class="local_logo">
    <a href="#"></a>
  </div>
</div>
<div>
  <div class="local_text">Third</div>
  <div class="local_logo">
    <img src="" alt="">
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

试试这个(使用.find()方法)

$('.local_logo div').each(function() {
    if ($(this).find('img').length) {
        // there is an image in this div, do anything here..
    }
});

它对我有用,也希望能解决你的问题:)

相关问题