此非常好用
document.getElementById("ddlResourceType").options.add(new Option(text,value));
下拉框:
<select id="ddlResourceType" οnchange="getvalue(this)"> </select>
1、動態刪除select中的所有options:
document.getElementById("ddlResourceType").options.length=0;
2、動態刪除select中的某一項option:
document.getElementById("ddlResourceType").options.remove(index);
3、動態添加select中的項option:
document.getElementById("ddlResourceType").options.add(new Option(text,value));
上面的操作在IE和火狐中都能測試成功,其實用標準的DOM操作也可以,就是document.createElement,appendChild,removeChild之類的。
4、下面要說下在取值方面,自己遇到的一個坑,很隱藏的坑,大家都知道,如何獲取選中的某一項option的值,當初在用chrome調試的時候,打印出了原生select對象,找到了selectedOptions這個選中項的數組屬性,正常情況下,單選下拉框的該屬性只有一個值,默認可以使用selectedOptions[0]這樣的方式去獲取,是的,我當時就是這樣去弄的,結果項目上線後大概將近半個月的時候,運營那邊報告說,客戶在IE瀏覽器下,下拉框沒有數據顯示,我當時就想,下拉框動態獲取的數據肯定是取數據的時候,出現錯誤了,然後逐一去排查,發現報錯的原因是ie下面select原生對象裏,是沒有selectedOptions這樣的屬性的,那麼只能另闢蹊徑來解決了,我仔細找了下剩餘的一些屬性,發現 找到了 selctedIndex這樣的一個好屬性,一看字面意思就明白了,就是選中項的index值啊,這就好辦了啊,直接用options[selectedIndex]去訪問不就好了麼,到此,問題順利解決:
取值的時候,應該這樣做,才能保證兼容性:
function getvalue(obj) { var m=obj.options[obj.selectedIndex].value alert(m);//獲取value var n=obj.options[obj.selectedIndex].text alert(n);//獲取文本 }
5、 檢測是否有選中
if (objSelect.selectedIndex > - 1 ) { // 說明選中 } else { // 說明沒有選中 }
6、刪除被選中的項
objSelect.options[objSelect.selectedIndex] = null ;
7、增加項
objSelect.options[objSelect.length] = new Option( " 你好 " , " hello " );
8、修改所選擇中的項
objSelect.options[objSelect.selectedIndex] = new Option( " 你好 " , " hello " );
9、得到所選擇項的文本
objSelect.options[objSelect.selectedIndex].text;
10、得到所選擇項的值
objSelect.options[objSelect.selectedIndex].value;