2012-01-27 43 views
2

使用.removeAttr(「selected」)從多選中的選項中刪除「selected」屬性時,選項不會立即在Chrome中重新繪製爲未選中狀態。使用Chrome開發人員工具監視DOM顯示所選屬性已從DOM中刪除,但仍然顯示選中選項,直到頁面上的其他項目獲得焦點。刷新通過jQuery刪除所選屬性後的多重選擇

有沒有辦法讓選項以編程方式重繪?我觸發了「更改」和其他一些事件,但除了讓用戶在適當的地方懸停或點擊,似乎沒有任何工作。似乎瀏覽器忘記重繪元素,直到其他人引起注意。

下面是相關代碼:

$("#selectAll").click(function() { 
    $("#x option").attr("selected", "selected"); 
}); 
$("#deselectAll").click(function() { 
    $("#x option").removeAttr("selected"); 
}); 

和標記:

<a id="selectAll" href="javascript:void(0)">Select All</a> 
<a id="deselectAll" href="javascript:void(0)">Deselect All</a> 

<select multiple="multiple" size="5" style="height: 6em;" name="x" id="x"> 
    <option>1</option> 
    <option>2</option> 
    <option>3</option> 
    <option>4</option> 
    <option>5</option> 
</select> 

這是jQuery的1.7.1和Chrome 16

回答

3

設置focus就可以了,並立即致電blur它的工作原理。嘗試這個。

$("#selectAll").click(function() { 
    $("#x option").attr("selected", "selected"); 
}); 
$("#deselectAll").click(function() { 
    $("#x").find("option") 
    .removeAttr("selected") 
    .end().focus().blur(); 
}); 

Demo

+0

謝謝,這是實際可行的。我仍然喜歡理解爲什麼有必要使元素重繪。 – 2012-01-27 17:55:40

0

嘗試刷新這樣的元素的寬度:

$("#selectAll").click(function() { 
    $("#x option").attr("selected", "selected"); 
}); 
$("#deselectAll").click(function() { 
    $("#x option").removeAttr("selected").width($("#x option").width()); 
}); 

jsFiddle