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
If element contains certain text
提问by UserIsCorrupt
$('.test').css('background','red');
<div id="example">Some text</div>
How can I .addClass('test')
if #example
contains the word "text"?
.addClass('test')
如果#example
包含“文本”一词,我该怎么办?
回答by Fabrizio Calderan
just use :contains
pseudoclass
只使用:contains
伪类
$('#example:contains("text")').addClass('test');
this will add the class to #example
if 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
. 但是,只有少数情况下速度真正重要。