jQuery if"this"包含 [英] jQuery if "this" contains
问题描述
我正在尝试将包含特定文本字符串的所有元素更改为红色.在我的示例中,我可以使子元素变为蓝色,但是我编写替换我"行的方式有些错误;红色不会发生变化.我注意到"contains"方法通常写为:contains
,但我无法通过$(this)
对其进行验证.
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)
.
$('#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');
}
});
提琴: http://jsfiddle.net/zatHH/
推荐答案
:contains
是选择器.要检查选择器是否适用于给定变量,可以使用 is
:
:contains
is a selector. To check if a selector applies to given variable, you can use is
:
if($(this).is(':contains("Replace Me")'))
在这种情况下,Vega的解决方案更干净.
However Vega's solution is cleaner in this case.
这篇关于jQuery if"this"包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!