Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 设置单选按钮组已选中_Javascript_Jquery_Radio Button_Attr - Fatal编程技术网

Javascript 设置单选按钮组已选中

Javascript 设置单选按钮组已选中,javascript,jquery,radio-button,attr,Javascript,Jquery,Radio Button,Attr,我试图将单选按钮组设置为默认选中状态,但我无法执行此操作。 我尝试以下方法: $('tr:first').closest('input:radio').attr('checked', true); $('tr:first td input:radio').each(function(){ $(this).attr('checked', true); }); $('tr:first').closest('input:radio').attr('checked', true); 请帮

我试图将单选按钮组设置为默认选中状态,但我无法执行此操作。 我尝试以下方法:

$('tr:first').closest('input:radio').attr('checked', true);


$('tr:first td input:radio').each(function(){
    $(this).attr('checked', true);
});

$('tr:first').closest('input:radio').attr('checked', true);

请帮助我,我如何解决这个问题。

最近的
将在层次结构中向上移动(即搜索父元素),我想您正在尝试查找
tr
中的单选按钮。在这种情况下,您可以使用
.find()
获取单选按钮,请参见下面的代码-

$('tr:first').find('input[type=radio]').prop('checked', true);

注意-在jQuery1.6中引入,earliar用于更改属性。现在,建议使用
.prop()
而不是
.attr()
来设置
选中的
属性,而不是
attr
。您的第二个代码块最接近正确(两个使用
closest
的代码块没有多大意义,
closest
查看祖先元素,单选按钮不能包含表行),但它会将
checked
设置为第一行中的所有单选按钮。如果这是您想要的,
prop
应该这样做:

$('tr:first td input:radio').each(function(){
    $(this).prop('checked', true);
});
$('tr:first td input:radio')。每个(函数(){
$(this.prop('checked',true);
});

第一排
第二排

我认为正确的语法是

.prop('checked', true);
不管你想做什么。 例如:

$('tr:first-child td input[type=radio]').each(function(){
    $(this).prop('checked', true);
});
解决这个问题:

$('tr:nth-child(2) td input:radio').each(function () {
       $(this).attr('checked', true);
   });

谢谢。问题出现在头一行。

tr
不能将收音机作为父项,因此肯定
最近的()
将永远无法工作。显示你的HTML。也显示你的HTML标记。你为什么不建议这样做<代码>$('tr:first td input:radio').prop('checked',true)@RajaprabhuAravindasamy:很好。林木问题。:-)
.attr('checked',true)不建议在设置元素属性时使用此选项。@RajaprabhuAravindasamy,更新了我的答案。。谢谢:)