jQuery:按类和输入类型选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1065925/
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
jQuery: Selecting by class and input type
提问by Brian Sullivan
I would like to select a set of elements that are both of a certain input type (say, a checkbox) and have a certain class using jQuery. However, when I try the following:
我想选择一组具有特定输入类型(例如复选框)并使用 jQuery 具有特定类的元素。但是,当我尝试以下操作时:
$("input:checkbox .myClass")
I don't get any items returned. How can I accomplish this in jQuery?
我没有得到任何退货。我怎样才能在 jQuery 中做到这一点?
回答by Paolo Bergantino
Your selector is looking for any descendants of a checkbox element that have a class of .myClass
.
您的选择器正在寻找类为.myClass
.
Try this instead:
试试这个:
$("input.myClass:checkbox")
I also tested this:
我也测试了这个:
$("input:checkbox.myClass")
And it will also work properly. In my humble opinion this syntax really looks rather ugly, as most of the time I expect :
style selectors to come last. As I said, though, either one will work.
它也将正常工作。以我的拙见,这种语法看起来相当丑陋,因为大多数时候我希望:
样式选择器排在最后。不过,正如我所说,任何一个都行。
回答by BaroqueBobcat
回答by eKek0
You have to use (for checkboxes) :checkbox
and the .name
attribute to select by class.
您必须使用(用于复选框):checkbox
和.name
要按类选择的属性。
For example:
例如:
$("input.aclass:checkbox")
The :checkbox
selector:
的:checkbox
选择:
Matches all input elements of type checkbox. Using this psuedo-selector like
$(':checkbox')
is equivalent to$('*:checkbox')
which is a slow selector. It's recommended to do$('input:checkbox')
.
匹配复选框类型的所有输入元素。使用这个 psuedo-selector like
$(':checkbox')
相当于$('*:checkbox')
which is a slow selector。建议做$('input:checkbox')
。
You should read jQuery documentationto know about selectors.
您应该阅读jQuery 文档以了解选择器。
回答by Akhil Chandran
回答by Fabio Padua
Try this:
尝试这个:
$("input:checkbox").hasClass("myClass");
回答by iforce2d
Just in case any dummies like me tried the suggestions here with a button and found nothing worked, you probably want this:
以防万一像我这样的傻瓜用按钮尝试了这里的建议但发现没有任何效果,你可能想要这个:
$(':button.myclass')