廢話不多說了,直接給大家貼代碼,具體代碼如下所示:
<!DOCTYPE html PUBLIC "-//WC//DTD XHTML . Transitional//EN" "http://www.w.org/TR/xhtml/DTD/xhtml-transitional.dtd"><html xmlns="http://www.w.org//xhtml"><head><title></title><!--添加jquery--><script src="../Script/jQuery/jquery-...min.js" type="text/javascript"></script><script type="text/javascript">$(function () {createSelect("select", "addSel");addOption("addSel", "first", "第一個數據");addOption("addSel", "secord", "第二個數據");addOption("addSel", "three", "第三個數據");addOption("addSel", "four", "第四個數據");addOption("addSel", "fives", "第五個數據");removeOneByIndex("addSel", );removeOneByObj("addSel", "secord");//添加一個option更改事件 調用自己寫的方法$("#addSel").change(function () {alert("舊文本:"+getOptionText("addSel") + "舊Value:" + getOptionValue("addSel"));editOptions("addSel", "新文本","新Value"); //注意:不傳value值的時候 value值默認為text的值alert("新文本:" + getOptionText("addSel") + "新Value:" + getOptionValue("addSel"));})})//動態創建帶id的元素function createSelect(element, id) {var select = document.createElement(element);select.id = id;document.body.appendChild(select);}//根據select的id 添加選項optionfunction addOption(selectID,value,text) {//根據id查找對象, var obj = document.getElementById(selectID); obj.options.add(new Option(text, value)); //這個兼容IE與firefox }//刪除所有選項optionfunction removeAll(selectID) {var obj = document.getElementById(selectID);obj.options.length = ;}//根據 index 值刪除一個選項optionfunction removeOneByIndex(selectID,index) {var obj = document.getElementById(selectID);//index,要刪除選項的序號,這里取當前選中選項的序號 //var index = obj.selectedIndex;//獲取選中的選項的index;obj.options.remove(index);}//根據 value或者text值刪除一個選項optionfunction removeOneByObj(selectID, textOrValue) {var obj = document.getElementById(selectID);//index,要刪除選項的序號,這里取當前選中選項的序號 //var index = obj.selectedIndex;//獲取選中的選項的index;for (var i = ; i < obj.options.length; i++) {if (obj.options[i].innerHTML == textOrValue || obj.options[i].value == textOrValue) {obj.options.remove(i);break;}}} //獲得一個Option Value;function getOptionValue(selectID){var obj = document.getElementById(selectID); var index=obj.selectedIndex; //序號,取當前選中選項的序號 var val = obj.options[index].value;return val;} //獲得一個option Text;function getOptionText(selectID) {var obj = document.getElementById(selectID); var index=obj.selectedIndex; //序號,取當前選中選項的序號 var val = obj.options[index].text;return val;}//修改選中的optionfunction editOptions(selectID,newText,newValue) {var obj = document.getElementById(selectID); var index=obj.selectedIndex; //序號,取當前選中選項的序號 obj.options[index] = new Option(newText, newValue);obj.options[index].selected = true;}//刪除selectfunction removeSelect(){var select = document.getElementById("select"); select.parentNode.removeChild(select); }</script></head><body></body></html>以上所述是小編給大家分享的JavaScript操作select元素和option的實例代碼,希望對大家有所幫助。
新聞熱點
疑難解答