问题描述
我有一个包含标签元素的列表项元素。我想用:has()
选择器来选择列表项元素。在标签元素内部,我想要匹配:contains()
。是否有可能用一行jQuery做这两件事情?如果不是,基于其子标签元素的内容选择li元素的优雅方法是什么?
I have a list item element that contains a label element. I want to select the list item element with the :has()
selector. Inside the label element there is text I want to match with :contains()
. Is it possible to do both of these things with a single line of jQuery? If not, what is an elegant way to select the li element based on the contents of its child label element?
<li>
<!-- I want to select this one -->
<label>Label 1</label>
<!-- more follows -->
</li>
推荐答案
您想要:
$("li:has(label):contains('Label 1')")
这将选择任何< li>
,两者都有< label&
,并在其中的任何位置包含文本标签1
。
This will select any <li>
that both has a <label>
and contains the text Label 1
anywhere inside of it.
$("li:has(label:contains('Label 1'))")
这将选择具有< label>
的任何< li>
文本标签1
。 (如果标签1
在< li>
。)
This will select any <li>
that has a <label>
and that label in particular contains the text Label 1
. (The first selector will match if "Label 1
" is anywhere inside the <li>
.)
这篇关于使用jQuery:has()和:contains()选择器在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!