Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

javascript - Combining a class selector and an attribute selector with jQuery

Is it possible to combine both a class selector and an attribute selector with jQuery?

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>

What would be the selector I can use to select rows 1 and 3 only?

I have tried:

$(".myclass [reference=12345]") // returns nothing

$(".myclass, [reference=12345]") // returns all 4 rows (yes, I know the comma means 'or')

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...