我正在尝试将包含特定文本字符串的任何元素更改为红色。在我的例子中,我可以让子元素变为蓝色,但是我写的“替换我”行的方式不正确;红色变化不会发生。我注意到“包含”方法通常写为:contains
但我无法通过$(this)
验证。
$('#main-content-panel .entry').each(function() {
$(this).css('color', 'blue');
});
$('#main-content-panel .entry').each(function() {
if($(this).contains("Replace Me").length > 0) {
$(this).css('color', 'red');
}
});
:contains
是一个选择者。要检查选择器是否适用于给定变量,您可以使用is
:
if($(this).is(':contains("Replace Me")'))
然而,在这种情况下,Vega的解决方案更清晰。
我不认为jQuery中有.contains
函数。
有一个.contains
函数,但该函数用于查看DOM元素是否是另一个DOM元素的后代。 See documentation for .contains.(致@beezir的积分)
我想你正在寻找:contains
选择器。请参阅下面的更多细节,
$('#main-content-panel .entry:contains("Replace Me")').css('color', 'red');
您可以使用match
查找特定元素内的文本
$('#main-content-panel .entry').each(function() {
$(this).css('color', 'blue');
});
$('#main-content-panel .entry').each(function() {
if($(this).text().match('Replace Me')) {
$(this).css('color', 'red');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main-content-panel">
<div class="entry">ABC</div>
<div class="entry">ABC Replace Me</div>
<div class="entry">ABC</div>
<div class="entry">ABC Replace Me</div>
</div>
我认为我们应该将我们的文本转换为小写。最好用小写和大写来检查。
$('#main-content-panel .entry').each(function() {
var ourText = $(this).text().toLowerCase(); // convert text to Lowercase
if(ourText.match('replace me')) {
$(this).css('color', 'red');
}
});