Javascript 将类选择器和属性选择器与 jQuery 结合使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6246683/
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
Combining a class selector and an attribute selector with jQuery
提问by Jason Child
Is it possible to combine both a class selector andan attribute selector with jQuery?
是否可以将类选择器和属性选择器与 jQuery 结合使用?
For example, given the following HTML:
例如,给定以下 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?
我只能用来选择第 1 行和第 3 行的选择器是什么?
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?
我确信答案非常简单,我已经尝试搜索 jQuery 论坛和文档,但我似乎无法弄清楚这一点。任何人都可以帮忙吗?
回答by BoltClock
Combine them. Literally combinethem; attachthem 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 selectoroperator — whatever that means (CSS selectors don't have a notion of "operators"; the comma is probably more accurately known as a delimiter).
你的第二个选择器,就像你说的,寻找具有属性值或类,或两者兼而有之的元素。
逗号被解释为多重选择器运算符——不管这意味着什么(CSS 选择器没有“运算符”的概念;逗号可能更准确地称为分隔符)。
回答by Nick Pyett
I think you just need to remove the space. i.e.
我认为你只需要删除空间。IE
$(".myclass[reference=12345]").css('border', '#000 solid 1px');
There is a fiddle here http://jsfiddle.net/xXEHY/
这里有一个小提琴http://jsfiddle.net/xXEHY/
回答by Daniel
This code works too:
此代码也有效:
$("input[reference=12345].myclass").css('border', '#000 solid 1px');
回答by Ajay Malhotra
This will also work:
这也将起作用:
$(".myclass[reference='12345']").css('border', '#000 solid 1px');