问题描述
是否可以将类选择器和属性选择器与jQuery结合使用?
Is it possible to combine both a class selector and an attribute selector with jQuery?
例如,给定以下HTML:
For example, given the following HTML:
<TABLE>
<TR class="myclass" reference="12345"><TD>Row 1</TD></TR>
<TR class="otherclass" reference="12345"><TD>Row 2</TD></TR>
<TR class="myclass" reference="12345"><TD>Row 3</TD></TR>
<TR class="myclass" reference="54321"><TD>Row 4</TD></TR>
</TABLE>
我只能用来选择第1行和第3行的选择器是什么?
What would be the selector I can use to select rows 1 and 3 only?
我尝试过:
$(".myclass [reference=12345]") // returns nothing
$(".myclass, [reference=12345]") // returns all 4 rows (yes, I know the comma means 'or')
我确信答案非常简单,我已经尝试搜索jQuery论坛和文档,但是我似乎无法弄清楚这一点.有人可以帮忙吗?
I'm sure the answer is very simple and I have tried searching the jQuery forums and documentation but I can't seem to figure this one out. Can anyone help?
推荐答案
组合它们.从字面上看组合它们;将它们附加在一起,没有任何标点符号.
Combine them. Literally combine them; attach them together without any punctuation.
$('.myclass[reference="12345"]')
您的第一个选择器将查找具有属性值的元素,该属性值包含在类的元素中.
该空间被解释为后代选择器.
Your first selector looks for elements with the attribute value, contained in elements with the class.
The space is being interpreted as the descendant selector.
您的第二个选择器,就像您说的那样,查找具有属性值或/或类或二者兼有的元素.
逗号被解释为多重选择器运算符-意味着什么(CSS选择器没有运算符"的概念;逗号可能更准确地称为定界符.
Your second selector, like you said, looks for elements with either the attribute value, or the class, or both.
The comma is being interpreted as the multiple selector operator — whatever that means (CSS selectors don't have a notion of "operators"; the comma is probably more accurately known as a delimiter).
这篇关于将类选择器和属性选择器与jQuery结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!