jquery - 根据内容将 CSS 样式应用于 span 标签

标签 jquery html css

我不知道这是否可行,但我正在尝试根据其内容将样式应用于 span 标记。

我在博客网站上有一些标签存储在 span 标签中,我想根据它们的内容设置样式。

$(“#col-cell.span:contains(‘c’)”).css(‘color’,’blue’);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-cell">
  <span>cloud</span>
  <span>business</span>
  <span>social</span>
</div>

我找到了这个 jQuery 命令,但运气不太好。

最佳答案

  1. col-cell 使用 . 而不是 # 因为它指的是一个类
  2. col-cellspan 之间使用空格 表示您正在搜索 child
  3. :contains() 本身中,不要使用引号

$('.col-cell span:contains(c)').css('color', 'blue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="col-cell">
  <span>cloud</span>
  <span>business</span>
  <span>social</span>
</div>

更新

hi i have managed to get it to work now, thank you, there one other thing, i would like to use another selector instead of :contain, and use a selector based on the first character of the word

来自 jQuery selector that simulates :starts-with or :ends-with for searching text?

$.extend($.expr[":"], {
    "starts-with": function(elem, i, data, set) {
        var text = $.trim($(elem).text()),
            term = data[3];

        // first index is 0
        return text.indexOf(term) === 0;
    },

    "ends-with": function(elem, i, data, set) {
        var text = $.trim($(elem).text()),
            term = data[3];

        // last index is last possible
        return text.lastIndexOf(term) === text.length - term.length;
    }
});
$('span:starts-with(c)').css('color', 'blue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="col-cell">
  <span>cloud</span>
  <span>business</span>
  <span>social</span>
</div>

关于jquery - 根据内容将 CSS 样式应用于 span 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31207051/

相关文章:

jquery - 通过javascript/jquery根据声音强度生成声波

jquery ajax 结果 div 向下滑动

javascript - HTML5 视频的后备图像

javascript - 匹配字符串的一部分

html - 所有输入字段应在同一行

jquery - 如何从HTML页面正确删除Flash对象

javascript - 检查文本区域是否已经存在

html - CSS动画。但是 Chrome 上什么也没有发生。显示正常标题

javascript - 如何在页面加载后淡入: Javascript

jquery - select2和远程数据: pre-set value and text avoiding server round-trip