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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:33:23  来源:igfitidea点击:

jQuery: Selecting by class and input type

jquery

提问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")

Check it out in action.

在行动中检查一下

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

If you want to get the inputs of that type with that class use:

如果要使用该类获取该类型的输入,请使用:

$("input.myClass[type=checkbox]")

the [] selector syntax allows you to check against any of the elements attributes. Check out the specfor more details

[] 选择器语法允许您检查任何元素属性。查看规范以获取更多详细信息

回答by eKek0

You have to use (for checkboxes) :checkboxand the .nameattribute to select by class.

您必须使用(用于复选框):checkbox.name要按类选择的属性。

For example:

例如:

$("input.aclass:checkbox")

The :checkboxselector:

: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

You should use the class name like this

你应该像这样使用类名

$(document).ready(function(){
    $('input.addCheck').prop('checked',true);
});

Try Using this a live demo

尝试使用这个 现场演示

回答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')