jQuery 如果“this”包含
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14510261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery if "this" contains
提问by Chris
I'm trying to change any elements containing a particular text string to a red color. In my example I can get the child elements to become blue, but there's something about the way I've written the 'Replace Me' line that is incorrect; the red color change doesn't happen. I note that the "contains" method is usually written as :contains
but I couldn't get that to validate with $(this)
.
我正在尝试将包含特定文本字符串的任何元素更改为红色。在我的示例中,我可以让子元素变为蓝色,但是我编写“替换我”行的方式有一些不正确;红色变化不会发生。我注意到“包含”方法通常被编写为,: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');
}
});
Fiddle: http://jsfiddle.net/zatHH/
回答by jkozera
回答by Selvakumar Arumugam
I don't think there is a There is a .contains
function in jQuery..contains
function but that function is used to see if a DOM element is a descendant of another DOM element. See documentation for .contains.(Credits to @beezir)
我认为有一个.contains
jQuery 中没有函数。.contains
函数,但该函数用于查看一个 DOM 元素是否是另一个 DOM 元素的后代。请参阅 .contains 的文档。(感谢@beezir)
I think you are looking for :contains
selector. See below for more details,
我认为您正在寻找:contains
选择器。请参阅下面的更多细节,
$('#main-content-panel .entry:contains("Replace Me")').css('color', 'red');
回答by mbharanidharan88
you can use match
to find the text inside the particular element
您可以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>
回答by KoemsieLy
I think we should convert our text to lower case. It is better to check with lowercase and uppercase.
我认为我们应该将我们的文本转换为小写。最好用小写和大写进行检查。
$('#main-content-panel .entry').each(function() {
var ourText = $(this).text().toLowerCase(); // convert text to Lowercase
if(ourText.match('replace me')) {
$(this).css('color', 'red');
}
});