標籤:class ext 事件 ted select 選中 col 執行 pen
1、擷取選中select的value和text,html代碼如下:
<select id="mySelect"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select>
$("#mySelect").val(); //擷取選中記錄的value值 $("#mySelect option:selected").text(); //擷取選中記錄的text值
2、運用new Option("文本","值")方法添加選項option
var obj = document.getElementById("mySelect");
obj.add(new Option("4","4"));
3、刪除所有選項option
var obj = document.getElementById("mySelect");
obj.options.length = 0;
4、刪除選中選項option
var obj = document.getElementById("mySelect");
var index = obj.selectedIndex;
obj.options.remove(index);
5、修改選中選項option
var obj = document.getElementById("mySelect"); var index = obj.selectedIndex; obj.options[index] = new Option("three",3); //更改對應的值 obj.options[index].selected = true; //保持選中狀態
6、刪除select
var obj = document.getElementById("mySelect"); obj.parentNode.removeChild(obj); //移除當前對象
7、select選擇的響應事件
$("#mySelect").change(function(){
//添加所需要執行的作業碼
})
1.動態建立select
function createSelect(){ var mySelect = document.createElement_x("select"); mySelect.id = "mySelect"; document.body.appendChild(mySelect); }
2.添加選項option
function addOption(){ //根據id尋找對象, var obj=document.getElementByIdx_x(‘mySelect‘); //添加一個選項 obj.add(new Option("文本","值")); //這個只能在IE中有效 obj.options.add(new Option("text","value")); //這個相容IE與firefox }
3.刪除所有選項option
function removeAll(){ var obj=document.getElementByIdx_x(‘mySelect‘); obj.options.length=0; }
4.刪除一個選項option
function removeOne(){ var obj=document.getElementByIdx_x(‘mySelect‘); //index,要刪除選項的序號,這裡取當前選中選項的序號 var index=obj.selectedIndex; obj.options.remove(index); }
5.獲得選項option的值
var obj=document.getElementByIdx_x(‘mySelect‘); var index=obj.selectedIndex; //序號,取當前選中選項的序號 var val = obj.options[index].value;
6.獲得選項option的文本
var obj=document.getElementByIdx_x(‘mySelect‘); var index=obj.selectedIndex; //序號,取當前選中選項的序號 var val = obj.options[index].text;
7.修改選項option
var obj=document.getElementByIdx_x(‘mySelect‘); var index=obj.selectedIndex; //序號,取當前選中選項的序號 var val = obj.options[index]=new Option("新文本","新值");
8.刪除select
function removeSelect(){ var mySelect = document.getElementByIdx_x("mySelect"); mySelect.parentNode.removeChild(mySelect); }
js 操作select和option常用代碼整理