使用 id 和类选择器检查 Jquery 设置单选按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15949324/
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 16:06:11  来源:igfitidea点击:

Jquery set radio button checked, using id and class selectors

jquerybuttonchecked

提问by Alan A

Is it possible to set a radio button to checked using jquery - by a class and an id?

是否可以使用 jquery 设置一个单选按钮来检查 - 通过一个类和一个 id?

For example:

例如:

$('input:radio[class=test1 id=test2]).attr('checked', true);

I only seem to be able to set it by id OR class but not by both.

我似乎只能通过 id 或 class 来设置它,但不能同时通过两者来设置。

回答by nnnnnn

"...by a class and a div."

“...通过一个类和一个 div。”

I assume when you say "div" you mean "id"? Try this:

我假设当你说“div”时你的意思是“id”?尝试这个:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value]style selectors because id has its own formatas does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

无需考虑您的[attributename=value]样式选择器,因为idclass一样有自己的格式,而且它们很容易组合,尽管考虑到 id 应该是唯一的,它本身就足够了,除非您的意思是“仅选择该元素如果它当前具有指定的类”。

Or more generally to select an input where you want to specify a multiple attribute selector:

或者更一般地选择要指定多属性选择器的输入

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

也就是说,用自己的方括号列出每个属性。

Note that unless you have a pretty old version of jQuery you should use .prop()rather than .attr()for this purpose.

请注意,除非您有一个相当旧版本的 jQuery,否则您应该使用.prop()而不是.attr()用于此目的。