我不知道这是否可行,但我正在尝试根据其内容将样式应用于 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 命令,但运气不太好。
最佳答案
- 对
col-cell
使用.
而不是#
因为它指的是一个类 - 在
col-cell
和span 之间使用空格 表示您正在搜索 child - 在
: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/