通过内容完全匹配选择元素 [英] Select element by exact match of its content
问题描述
好吧,我想知道是否有一种方法可以使:contains()
jQuery的选择器仅使用 键入的字符串来选择元素
All right, I wonder if there is a way to make the :contains()
jQuery's selector to select elements with only the string that is typed in
例如-
<p>hello</p>
<p>hello world</p>
$('p:contains("hello")').css('font-weight', 'bold');
选择器将同时选择两个p
元素并将其设为粗体,但我希望它仅选择第一个.
The selector will select both p
elements and make them bold, but I want it to select only the first one.
推荐答案
不,没有jQuery(或CSS)选择器可以做到这一点.
No, there's no jQuery (or CSS) selector that does that.
您可以随时使用 filter
:
You can readily use filter
:
$("p").filter(function() {
return $(this).text() === "hello";
}).css("font-weight", "bold");
它不是选择器,但可以完成任务. :-)
It's not a selector, but it does the job. :-)
如果要在"hello"之前或之后处理空格,则可以抛出 $.trim
在其中:
If you want to handle whitespace before or after the "hello", you might throw a $.trim
in there:
return $.trim($(this).text()) === "hello";
对于那里的过早的优化器,如果您不关心它是否与<p><span>hello</span></p>
和类似内容不匹配,则可以直接使用innerHTML
来避免调用$
和text
:>
For the premature optimizers out there, if you don't care that it doesn't match <p><span>hello</span></p>
and similar, you can avoid the calls to $
and text
by using innerHTML
directly:
return this.innerHTML === "hello";
...但是您必须要有 很多 的段落,这样才很重要,以至于您可能首先遇到其他问题. :-)
...but you'd have to have a lot of paragraphs for it to matter, so many that you'd probably have other issues first. :-)
这篇关于通过内容完全匹配选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!