1. 程式人生 > >js select option物件小結

js select option物件小結

 先講jquery方式,再講原生方式

jquery方式

選擇框

jQuery獲取Select選擇的Text和Value:

語法解釋:

1. $("#select_id").change(function(){//code...});   //為Select新增事件,當選擇其中一項時觸發

2. var checkText=$("#select_id").find("option:selected").text();  //獲取Select選擇的Text

3. var checkValue=$("#select_id").val();  //獲取Select選擇的Value

4. var checkIndex=$("#select_id ").get(0).selectedIndex;  //獲取Select選擇的索引值

5. var maxIndex=$("#select_id option:last").attr("index");  //獲取Select最大的索引值 

6.var cc1 = $(".formc select[@name='country'] option[@selected]").text(); //得到下拉選單的選中項的文字(注意中間有空格)

7.var cc2 = $('.formc select[@name="country"]').val(); //得到下拉選單的選中項的值

8.var cc3 = $('.formc select[@name="country"]').attr("id"); //得到下拉選單的選中項的ID屬性值

9.$("#select").empty();//清空下拉框 //$("#select").html('');

10.$("<option value='1'>1111</option>").appendTo("#select")//新增下拉框的option

11.$('#select_id')[0].selectedIndex = 1; //select下拉框的第二個元素為當前選中值 

12.var item = $("select[@name=items] option[@selected]").text(); //獲 取select被選中項的文字 

稍微解釋一下:

1.select[@name='country'] option[@selected] 表示具有name 屬性,

並 且該屬性值為'country' 的select元素 裡面的具有selected 屬性的option 元素;

可以看出有@開頭的就表示後面跟 的是屬性。

jQuery設定Select選擇的 Text和Value:

語法解釋:

1. $("#select_id ").get(0).selectedIndex=1;  //設定Select索引值為1的項選中

2. $("#select_id ").val(4);   // 設定Select的Value值為4的項選中

3. $("#select_id option[text='jQuery']").attr("selected", true);   //設定Select的Text值為jQuery的項選中

jQuery新增/刪除Select的Option項:

語法解釋:

1. $("#select_id").append("<option value='Value'>Text</option>");  //為Select追加一個Option(下拉項)

2. $("#select_id").prepend("<option value='0'>請選擇</option>");  //為Select插入一個Option(第一個位置)

3. $("#select_id option:last").remove();  //刪除Select中索引值最大Option(最後一個)

4. $("#select_id option[index='0']").remove();  //刪除Select中索引值為0的Option(第一個)

5. $("#select_id option[value='3']").remove();  //刪除Select中Value='3'的Option

5. $("#select_id option[text='4']").remove();  //刪除Select中Text='4'的Option

遍歷option和新增、移除option

function changeShipMethod(shipping){

var len = $("select[@name=ISHIPTYPE] option").length

if(shipping.value != "CA"){

$("select[@name=ISHIPTYPE] option").each(function(){

if($(this).val() == 111){

$(this).remove();

}

});

}else{

$("<option value='111'>UPS Ground</option>").appendTo($("select[@name=ISHIPTYPE]"));

}

}

附:

單選框:

$("input[@type=radio][@checked]").val(); //獲取值

$("input[@type=radio][@checked]").val(); //得到單選框的 選中項的值(注意中間沒有空格)

$("input[@type=radio][@value=2]").attr("checked",'checked'); //設定單選框value=2的為選中狀態.(注意中間沒有空格)

$('input[@name=items]').get(1).checked = true; //radio單選組的第二個元素為當前選中值 

var item = $('input[@name=items][@checked]').val(); //獲 取一組radio被選中項的值 

$("input[@type=radio]").attr("checked",'2');//設定value=2的專案為當前選中項 

複選框:

$("#checkbox_id").attr("value"); //獲取值

$("input[@type=checkbox][@checked]").val(); //得到複選框的選中的第一項的值

$("input[@type=checkbox][@checked]").each(function() { //由於複選框一般選中的是多個,所以可以迴圈輸出

$("#chk1").attr("checked",'');//不打勾

$("#chk2").attr("checked",true);// 打勾

if($("#chk1").attr('checked')==undefined){} //判斷是否已經打勾

原生方式

一基礎理解:

var e = document.getElementById("selectId");

e. options= new Option("文字","值") ;

//建立一個option物件,即在<select>標籤中建立一個或多個<option value="值">文字</option>

//options是個陣列,裡面可以存放多個<option value="值">文字</option>這樣的標籤

1:options[ ]陣列的屬性:

length屬性---------長度屬性

selectedIndex屬性--------當前被選中的框中的文字的索引值,此索引值是記憶體自動分配的(0,1,2,3.....)對應(第一個文字值,第二個文字值,第三個文字值,第四個文字值..........)

2:單個option的屬性(---obj.options[obj.selecedIndex]是指定的某個<option>標籤,是一個---)

text屬性---------返回/指定 文字

value屬性------返回/指定 值,與<options value="...">一致。

index屬性-------返回下標,

selected 屬性-------返回/指定該物件是否被選中.通過指定 true 或者 false,可以動態的改變選中項

defaultSelected 屬性-----返回該物件預設是否被選中。true / false。

3:option的方法

增加一個<option>標籤-----obj.options.add(new("文字","值"));<增>

刪除一個<option>標籤-----obj.options.remove(obj.selectedIndex)<刪>

獲得一個<option>標籤的文字-----obj.options[obj.selectedIndex].text<查>

修改一個<option>標籤的值-----obj.options[obj.selectedIndex]=new Option("新文字","新值")<改>

刪除所有<option>標籤-----obj.options.length = 0

獲得一個<option>標籤的值-----obj.options[obj.selectedIndex].value

注意:

a:上面的寫的是如這樣型別的方法obj.options.function()而不寫obj.funciton,是因為為了考慮在IE和FF 下的相容,如obj.add()只能在IE中有效.

b:obj.option中的option不需要大寫,new Option中的Option需要大寫

二 應用 

<html> 
<head> 
<script language="javascript"> 
function number(){ 
var obj = document.getElementById("mySelect"); 
    //obj.options[obj.selectedIndex] = new Option("我的吃吃","4");//在當前選中的那個的值中改變 
    //obj.options.add(new Option("我的吃吃","4"));再新增一個option 
    //alert(obj.selectedIndex);//顯示序號,option自己設定的 
    //obj.options[obj.selectedIndex].text = "我的吃吃";更改值 
   //obj.remove(obj.selectedIndex);刪除功能 
} 
</script> 
</head> 
<body> 
<select id="mySelect"> 
     <option>我的包包</option> 
     <option>我的本本</option> 
     <option>我的油油</option> 
     <option>我的擔子</option> 
</select> 
<input type="button" name="button" value="檢視結果" onclick="number();"> 
</body> 
</html> 


根據這些東西,自己用JQEURY AJAX+JSON實現了一個小功能如下:

JS程式碼:(只取了於SELECT相關的程式碼) 

/** 
   * @description  構件聯動下拉列表 (用JQUERY 的AJAX配合JSON實現) 
   * @prarm  selectId 下拉列表的ID 
   * @prarm  method  要呼叫的方法名稱 
   * @prarm  temp 此處存放軟體ID 
   * @prarm  url  要跳轉的地址 
   */ 
function  linkAgeJson(selectId,method,temp,url){    
      $j.ajax({     
            type: "get",//使用get方法訪問後臺 
            dataType: "json",//返回json格式的資料 
            url: url,//要訪問的後臺地址 
            data: "method=" + method+"&temp="+temp,//要傳送的資料         
            success: function(msg){//msg為返回的資料,在這裡做資料繫結 
                var data = msg.lists; 
                coverJsonToHtml(selectId,data);              
            } 
        }); 
}
/** 
* @description  將JSON資料轉換成HTML資料格式 
* @prarm selectId 下拉列表的ID 
* @prarm  nodeArray 返回的JSON陣列 
* 
*/ 
function coverJsonToHtml(selectId,nodeArray){ 
//get select 
   var tempSelect=$j("#"+selectId); 
   //clear select value 
   isClearSelect(selectId,'0');    
var tempOption=null; 
for(var i=0;i<nodeArray.length;i++){ 
//create select Option 
tempOption= $j('<option value="'+nodeArray[i].dm+'">'+nodeArray[i].mc+'</option> '); 
//put Option to select 
tempSelect.append(tempOption); 
        } 
        // 獲取退化構件列表 
       getCpgjThgl(selectId,'thgjDm'); 
   } 
   /** 
   * @description  清空下拉列表的值 
   * @prarm selectId 下拉列表的ID 
   * @prarm index 開始清空的下標位置 
   */ 
  function isClearSelect(selectId,index){ 
     var length=document.getElementById(selectId).options.length; 
while(length!=index){ 
      //長度是在變化的,因為必須重新獲取  
          length=document.getElementById(selectId).options.length; 
          for(var i=index;i<length;i++) 
             document.getElementById(selectId).options.remove(i); 
         length=length/2; 
     } 
   } 

/** 
* @description 獲取退化構件列表 
* @prarm  selectId1 引用軟體下拉列表的ID 
* @prarm  selectId2 退化構件下拉列表的ID 
*/ 
   function getCpgjThgl(selectId1,selectId2){ 
   var obj1=document.getElementById(selectId1);//引用軟體下拉列表 
   var obj2=document.getElementById(selectId2);//退化構件下拉列表 
   var len=obj1.options.length; 
  //當引用軟體列表長度等於1時返回,不做操作 
   if(len==1){ 
          return false; 
   } 
   //清空下拉列表的值,兩種方式都可以 
  // isClearSelect(selectId2,'1');  
            document.getElementById(selectId2).length=1; 
   for(var i=0;i<len; i++){ 
var option= obj1.options[i];  
//引用軟體被選中項不加入 
if(i!=obj1.selectedIndex){ 
//克隆OPTION並新增到SELECT中   
obj2.appendChild(option.cloneNode(true)); 
}  
}
   }  


HTML程式碼: 

<TABLE width="100%" border=0 align="left" cellPadding=0 cellSpacing=1> 
  <tr> 
<td  class="Search_item_18">  <span class="Edit_mustinput">*</span>引用軟體:</td> 
<td  class="Search_content_82"> 
<input name="yyrjMc" id="yyrjMc" type="text" class="Search_input" tabindex="3"  size="30" > 
<input name="yyrjDm" id="yyrjDm" type="hidden" > 
<input type="button" class="Search_button_select" 
onClick="linkAgeTree('linkage','yyrjtree','yyrjMc','yyrjDm','linkageTree','1');" value="選擇..."> 
</td> 
  </tr> 
  <tr> 
<td class="Search_item"> <span class="Edit_mustinput">*</span>引用分版:</td> 
<td  class="Search_content" id="yyfb"> 
  <select name="yyfbDm" style="width:160" id="yyfbDm" onChange="getCpgjThgl('yyfbDm','thgjDm')">
  </select> 
</td> 
  </tr> 
  <tr> 
<td class="Search_item">退化構件:</td> 
<td  class="Search_content" id="thgj"> 
   <select name="thgjDm" style="width:160" id="thgjDm"> 
<option value="-1" selected>無</option> 
   </select> 
</td> 
  </tr> 
</TABLE> 

參考文件:

http://www.jb51.net/article/44657.htm

https://blog.csdn.net/wybshyy/article/details/80596066