關於jQuery中.attr()和.prop()的問題探討

來源:互聯網
上載者:User

話說寫了幾句代碼在ie8上能正常運行,chrome和ff卻不行,朋友說這就是RP啊,鬱悶!

其實功能需求是這樣的,兩個radio:男和女,一個button:重設。啟動頁面預設選中男,在使用者選擇女之後又點擊重設按鈕,需要恢複到預設狀態。
複製代碼 代碼如下:
<input type="radio" id="hRdMale" checked="checked" name="sex" value="male" /><label for="hRdMale">男</label>
<input type="radio" id="hRdFemale" name="sex" value="female" /><label for="hRdFemale">女</label>
<button id="reSet">重設</button>

我的js代碼是這樣的:
複製代碼 代碼如下:
$("#reSet").click(function() {
  $("input[name='sex']:first").attr("checked",true);
});

結果就是開頭提到的樣子,問了幾個人都說不清楚,後來查了API後知道在jQuery1.6+的版本中添加了.prop()的方法,貌似和.attr()沒什麼區別,都可以用來擷取和設定屬性值。後來又瞭解到.prop()方法適用於Boolean值的屬性,官方解釋selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 以及defaultSelected 等屬性需用.prop()方法。另外,看網上還有好多說“添加屬性名稱該屬性就會生效應該使用.prop()”,本人沒驗證其他屬性,倒是"checked"屬性的確是添加就生效。所以,紅色的兩點應該就是.attr()和.prop()的區別所在了。

所以,將上面click事件方法裡面的代碼改成下面的就OK了。
複製代碼 代碼如下:
$("input[name='sex']:first").prop("checked",true);

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.