当jquery被设置为true时,它没有得到选中的输入,然后其他人被设置为false
问题描述:
我看到了jQuery的一个有趣的行为,我不知道为什么,现在它不是真的问题,因为我“修复”它,但我想与大家分享这个,看代码:当jquery被设置为true时,它没有得到选中的输入,然后其他人被设置为false
switch(id){
case "1k":
check5k.attr('checked', false);
check10k.attr('checked', false);
check1k.attr('checked', true);
image1k.attr('class', 'radio-checked1k');
image5k.attr('class', 'radio5k');
image10k.attr('class', 'radio10k');
break;
case "5k":
check1k.attr('checked', false);
check10k.attr('checked', false);
check5k.attr('checked', true);
image1k.attr('class', 'radio1k');
image5k.attr('class', 'radio-checked5k');
image10k.attr('class', 'radio10k');
break;
case "10k":
check1k.attr('checked', false);
check5k.attr('checked', false);
check10k.attr('checked', true);
image1k.attr('class', 'radio1k');
image5k.attr('class', 'radio5k');
image10k.attr('class', 'radio-checked10k');
break;
}
所以,它的工作原理,当我尝试alert($("input:checked").val())
,它让我看到当前选择的无线电值,但是,如果我这样做:
switch(id){
case "1k":
check1k.attr('checked', true);
check5k.attr('checked', false);
check10k.attr('checked', false);
image1k.attr('class', 'radio-checked1k');
image5k.attr('class', 'radio5k');
image10k.attr('class', 'radio10k');
break;
case "5k":
check1k.attr('checked', false);
check5k.attr('checked', true);
check10k.attr('checked', false);
image1k.attr('class', 'radio1k');
image5k.attr('class', 'radio-checked5k');
image10k.attr('class', 'radio10k');
break;
case "10k":
check1k.attr('checked', false);
check5k.attr('checked', false);
check10k.attr('checked', true);
image1k.attr('class', 'radio1k');
image5k.attr('class', 'radio5k');
image10k.attr('class', 'radio-checked10k');
break;
}
并试图做出同样的alert($("input:checked").val())
它显示的价值仅为10k id,其他显示为未定义。 10k显示了这个值,因为这是最后一个在这种情况下设置为真的值。
为什么发生?
答
您正在设置checked属性错误。在jQuery中,你可以用.attr('checked', 'checked')
来设置它,而.removeAttr('checked')
可以取消它。*
*在jQuery 1.6之前。 1.6后,您使用prop。
取决于jQuery的版本是...但自1.6以来,如果你使用.attr()你会得到'checked'并且.prop()你会得到'true' – devnull69