检查div内部是否有图像,然后采取措施



如果存在<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");
};

使用:has()选择器

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

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

jQuery(".local_logo:has(img)").prev(".local_text").addClass("half");
.half {
  background: green;
}
<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>

我建议:

// 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()中适当调整选择器。

参考文献:

  • find()
  • next()
  • toggleClass()

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

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

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

最新更新