jQuery 1.6.1上場救援,不用改寫attr()囉
jQuery 1.6正式版發表不過10天,jQuery 1.6.1正式版就接著登場囉!
在jQuery 1.6筆記中有特別提到.prop()/.attr()的Break Change,將導致很多使用attr(“selected”), attr(“checked”)寫法的程式爆炸,必須修改後才能套用jQuery 1.6。很顯然,這個不向前相容的決定引起開發社群強烈反彈,即便此舉是往正確方向移動,但打破相容性影響重大,成千上萬的程式必須因此修改,產生可觀的升級成本,同時這也可能導致開發人員不願升級新版jQuery,於是jQuery開發團隊從善如流,決定回歸"先研究不傷身體,再講求效果"的精神,在jQuery 1.6.1版調整.attr()存取邏輯,使其與1.5.2版本之前的做法相容。
這意味著:
$(“:checkbox”).attr(“checked”, true);
$(“option”).attr(“selected”, true);
$(“input”).attr(“readonly”, true);
$(“input”).attr(“disabled”, true);
if ( $(“:checkbox”).attr(“checked”) ) { /* Do something */ }
等寫法在jQuery 1.6.1裡可以繼續順利運作,但仍有些建議:
- $(window).attr(), $(document).attr()建議改為$(windows).prop(), $(document).prop(),因為window及document理論上無從加上HTML Attribute,雖然jQuery 1.6.1在內部會偷偷改用.prop(),畢竟語意不合邏輯,應該避免。
- 在HTML語法<input type=”checkbox” checked=”checked” />中,checked Attribute只會在一開始將checked Property設成true,後續的狀態變更及儲存都是透過checked Property。換句話說,checked Attribute只影響初值,之後應以checked Property為準。基於這個理由,$(":checkbox”).prop(“checked”, true)會比$(":checkbox”).attr(“checked”, true)來得合理。雖然jQuery 1.6.1已讓$(":checkbox”).attr(“checked”, true)也具有變更checked Property的能力,但prop()確實比attr()寫法更吻合背後的實際運作。
適用此點的Boolean屬性包含了: autofocus, autoplay, async, checked, controls, defer, disabled, hidden, loop, multiple, open, readonly, required, scoped, selected
另外,jQuery Team提供一張DOM元素屬性適用attr()/prop()的對照表:
Attribute/Property |
.attr() |
.prop() |
accesskey |
✓ |
|
align |
✓ |
|
async |
✓ |
✓ |
autofocus |
✓ |
✓ |
checked |
✓ |
✓ |
class |
✓ |
|
contenteditable |
✓ |
|
defaultValue |
|
✓ |
draggable |
✓ |
|
href |
✓ |
|
id |
✓ |
|
label |
✓ |
|
location * |
✓ |
✓ |
multiple |
✓ |
✓ |
nodeName |
|
✓ |
nodeType |
|
✓ |
readOnly |
✓ |
✓ |
rel |
✓ |
|
selected |
✓ |
✓ |
selectedIndex |
|
✓ |
src |
✓ |
|
style |
✓ |
|
tabindex |
✓ |
|
tagName |
|
✓ |
title |
✓ |
|
type |
✓ |
|
width ** |
✓ |
|
結論: 針對Boolean型別屬性或是沒有對應HTML Attribute者(例如: window.location)建議使用.prop(),其餘則可使用.attr()。[註: 紅色部分為可支援,但不建議使用]