JavaScript如何從listbox裡同時刪除多重專案

來源:互聯網
上載者:User

要從列表框同時刪除多重專案,我們不能從上到下的刪除,因為上面的項目每刪除一個,下面的項目的索引號就會變化,所以只能從下向上刪除,這樣就不會出現索引號亂變的問題了。

html代碼
複製代碼 代碼如下:
<table>
<tr>
<td align="center">
<select id="lsbox" name="lsbox" size="10" multiple>
<option value="1">India</option>
<option value="2">United States</option>
<option value="3">China</option>
<option value="4">Italy</option>
<option value="5">Germany</option>
<option value="6">Canada</option>
<option value="7">France</option>
<option value="8">United Kingdom</option>
</select>
</td>
</tr>
<tr>
<td align="center">
<button onclick="listbox_remove('lsbox');">Delete</button>
<button onclick="window.location.reload();">Reset</button>
</td>
</tr>
</table>

javascript代碼如下:
複製代碼 代碼如下:
function listbox_remove(sourceID) {
//get the listbox object from id.
var src = document.getElementById(sourceID);

//iterate through each option of the listbox
for(var count= src.options.length-1; count >= 0; count--) {

//if the option is selected, delete the option
if(src.options[count].selected == true) {

try {
src.remove(count, null);

} catch(error) {

src.remove(count);
}
}
}
}

當然,如果使用jQuery來刪除,那就方便了,一句話就搞定了
複製代碼 代碼如下:
$("#sourceId").find('option:selected').remove();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.