javascript 如果元素包含某些文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10329477/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:30:07  来源:igfitidea点击:

If element contains certain text

javascriptjquery

提问by UserIsCorrupt

$('.test').css('background','red');

<div id="example">Some text</div>

How can I .addClass('test')if #examplecontains the word "text"?

.addClass('test')如果#example包含“文本”一词,我该怎么办?

回答by Fabrizio Calderan

just use :containspseudoclass

只使用:contains伪类

$('#example:contains("text")').addClass('test');

this will add the class to #exampleif it contains 'text'

#example如果它包含“文本”,这会将类添加到

回答by T.J. Crowder

You can use $("#example")to get a jQuery wrapper for the element, then use text()to get its text, and use String#indexOf, e.g.:

您可以使用$("#example")获取元素的 jQuery 包装器,然后使用text()获取其文本,并使用String#indexOf,例如:

var ex = $("#example");
if (ex.text().indexOf("text") !== -1) {
    ex.addClass("test");
}

You can also use :contains("text")in the selector as F. Calderan shows, although note that when you use non-standard pseudo-selectors like that, jQuery can't use the underlying browser's built-in stuff for finding elements, so it can be slower. The above will allow jQuery to use document.getElementById. There are only a few situations where the speed really matters, though.

您也可以:contains("text")F. Calderan 展示的那样在选择器中使用,但请注意,当您使用像这样的非标准伪选择器时,jQuery 无法使用底层浏览器的内置内容来查找元素,因此它可能会更慢。以上将允许 jQuery 使用document.getElementById. 但是,只有少数情况下速度真正重要。

回答by Mark Walters

try the following code

试试下面的代码

$('#example:contains("text")').addClass('test');

Have a look herefor examples and explanations of the :containsselector

看看这里的实例和解释的:contains选择