如果div包含特定单词,则使用jquery在父div中添加一个新类 [英] If div contains specific word add a new class in parent div using jquery

查看:45
本文介绍了如果div包含特定单词,则使用jquery在父div中添加一个新类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是HTML代码:

<div class="menu-3-cat">
<div class="menu-item-category">Offer</div>
</div> 

这是jquery

if ($('.menu-item-category').text() === 'Offer') {
$('.menu-3-cat').addClass('make-me-red');
}

应该可以正常工作,并将类"make-me-red"添加到父div"menu-3-cat"中,但事实并非如此.我在做什么错了?

It should be work and add the class "make-me-red" to the parent div "menu-3-cat" but it doesn't. What i 'm doing wrong?

JSFiddle 这里

JSFiddle HERE

推荐答案

根据您的JSFiddle和注释,您需要遍历所选元素,比较与该类选择器匹配的每个元素的text().否则, text() 将返回每个文本的"组合文本内容".匹配元素集合中的元素".

Based on your JSFiddle and your comments, you will need to iterate over the selected elements, comparing the text() for each element that matches that class selector. Otherwise, text() will return the "combined text contents of each element in the set of matched elements".

我还添加了 trim() ,以便从元素的文本内容.

I've also added trim() to strip away any white space from the elements' text contents.

var $categories = $('.menu-item-category');

$categories.each(function() {
  var $this = jQuery(this);
  if ($this.text().trim() == 'Offer') {
    $this.closest('.menu-3-cat').addClass('make-me-red');
  }
});

.menu-3-cat {
  position: relative;
  overflow: hidden;
}

.make-me-red {
  background: #F44336;
  color: #ffffff;
}

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

<div class="menu-3-cat">
  <div class="menu-item-category">
    Things
  </div>
</div>
<div class="menu-3-cat">
  <div class="menu-item-category">
    Offer
  </div>
</div>
<div class="menu-3-cat">
  <div class="menu-item-category">
    Stuff
  </div>
</div>

这篇关于如果div包含特定单词,则使用jquery在父div中添加一个新类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆