需求:對radio的checked屬性先消除然后進行重新設置;
初步方案:
$("auForm input :radio[value='0']").removeAttr('checked'); $("auForm input :radio[value='1']").removeAttr('checked'); if(l.isover==0) $("auForm input :radio[value='0']").attr('checked','true'); if(l.isover==1) $("auForm input :radio[value='1']").attr('checked','true');
實際問題:在使用removeAttr()移除了radio的checked屬性后,使用attr()重新增加不起作用;
解決方法:
$("#auForm input:radio[value='1']").removeAttr('checked'); $("#auForm input:radio[value='0']").removeAttr('checked'); if(l.isover==1) $("#auForm input:radio[value='1']").prop('checked','true'); if(l.isover==0) $("#auForm input:radio[value='0']").prop('checked','true');
即使用prop()可重新配置上該屬性;
為此去查了一下關於jquery中關於attr()和prop()的使用:
從 jQuery 1.6 開始新增了一個方法 prop(),因為在 jQuery 1.6 之前,使用 attr() 有時候會出現不一致的行為。
根據官方的建議:具有 true 和 false 兩個屬性的屬性,如 checked, selected 或者 disabled 使用prop(),其他的使用 attr(),
詳情可參看該博客:http://wenzhixin.net.cn/2013/05/24/jquery_attr_prop。