DIV CSS 佈局教程網

JavaScript 完全掌握 Select 下拉選單:Option 增刪改查與聯動實作
編輯:關於JavaScript     

HTML 中的 <select> 標籤(在 ASP.NET 裡對應 asp:DropDownList 控制項)是表單開發最常打交道的元件。只要摸透 options 集合與 Option 建構子,新增、刪除、修改、取值全都難不倒你。

一、基礎理解

var e = document.getElementById("selectId");
e.options = new Option("文本", "值");

這行程式的意思是:建立一個 option 物件,等價於在 <select> 裡插入一個 <option value="值">文本</option>。而 options 本質上是一個集合,可以存放多個 option。

1. options 集合的屬性

length:選項數量。
selectedIndex:目前選中項的索引,由瀏覽器自動維護(0, 1, 2, 3…… 依序對應第一、二、三、四個選項)。

2. 單一 option 的屬性

obj.options[obj.selectedIndex] 指的就是某一個 option 節點,它具備下列屬性:

text:讀取或設定顯示文字。
value:讀取或設定值,與 <option value="..."> 一致。
index:回傳該選項的索引。
selected:讀取或設定是否被選中,指定 true / false 即可動態改變選中項。
defaultSelected:回傳預設是否被選中。

3. 常用操作速查

// 新增
obj.options.add(new Option("文本", "值"));
// 刪除目前選中項
obj.options.remove(obj.selectedIndex);
// 讀取目前選中項的文字 / 值
obj.options[obj.selectedIndex].text;
obj.options[obj.selectedIndex].value;
// 修改目前選中項
obj.options[obj.selectedIndex] = new Option("新文本", "新值");
// 清空全部選項
obj.options.length = 0;

兩個容易踩到的細節:

其一,刻意寫成 obj.options.add() 而不是 obj.add(),是為了兼顧 IE 與 Firefox——後者只在 IE 有效。
其二,obj.options 中的 options 用小寫,而 new Option() 的 Option 必須大寫。

二、應用實戰

<select id="mySelect">
  <option>我的包包</option>
  <option>我的本本</option>
  <option>我的油油</option>
  <option>我的擔子</option>
</select>
<input type="button" value="查看結果" onclick="number();" />

<script>
function number(){
  var obj = document.getElementById("mySelect");
  // obj.options.add(new Option("我的吃吃","4"));       // 新增
  // obj.options[obj.selectedIndex] = new Option("我的吃吃","4"); // 取代目前項
  // alert(obj.options[obj.selectedIndex].text = "我的吃吃");    // 改文字
  // obj.options.remove(obj.selectedIndex);             // 刪除
}
</script>

動態建立 select

function createSelect(){
  var mySelect = document.createElement("select");
  mySelect.id = "mySelect";
  document.body.appendChild(mySelect);
}

新增與清空選項

function addOption(){
  var obj = document.getElementById('mySelect');
  obj.options.add(new Option("text", "value")); // 相容 IE 與 Firefox
}
function removeAll(){
  document.getElementById('mySelect').options.length = 0;
}

刪除單一選項、取值與取文字

function removeOne(){
  var obj = document.getElementById('mySelect');
  obj.options.remove(obj.selectedIndex); // 傳入要刪除的索引
}

var obj = document.getElementById('mySelect');
var index = obj.selectedIndex;
var val = obj.options[index].value; // 值
var txt = obj.options[index].text;  // 文字

整個 select 移除

function removeSelect(){
  var mySelect = document.getElementById("mySelect");
  mySelect.parentNode.removeChild(mySelect);
}

用 createElement 組出二級聯動

function $(id){ return document.getElementById(id); }

function show(){
  var selectObj = $("area");
  var opt1 = document.createElement("option");
  opt1.setAttribute("value", "10");
  opt1.appendChild(document.createTextNode("上海"));
  var opt2 = document.createElement("option");
  opt2.setAttribute("value", "100");
  opt2.appendChild(document.createTextNode("南京"));
  selectObj.appendChild(opt1);
  selectObj.appendChild(opt2);
}

function choice(){
  var index = $("area").selectedIndex;
  var val = $("area").options[index].getAttribute("value");
  var box = $("context");
  if (box.childNodes.length) box.childNodes[box.childNodes.length - 1].removeNode(true);
  if (val == 10) {
    var sh = document.createElement("select");
    sh.add(new Option("浦東新區", "101"));
    sh.add(new Option("黃浦區", "102"));
    sh.add(new Option("徐匯區", "103"));
    sh.add(new Option("普陀區", "104"));
    box.appendChild(sh);
  }
  if (val == 100) {
    var nj = document.createElement("select");
    nj.add(new Option("玄武區", "201"));
    nj.add(new Option("白下區", "202"));
    nj.add(new Option("下關區", "203"));
    nj.add(new Option("棲霞區", "204"));
    box.appendChild(nj);
  }
}

三、進階:jQuery + AJAX + JSON 實作聯動下拉

/** 以 jQuery 的 AJAX 搭配 JSON 實作下拉聯動
 * @param selectId 下拉列表的 ID
 * @param method   要呼叫的後端方法
 * @param temp     傳遞參數
 * @param url      後端位址
 */
function linkAgeJson(selectId, method, temp, url){
  $j.ajax({
    type: "get",
    dataType: "json",
    url: url,
    data: "method=" + method + "&temp=" + temp,
    success: function(msg){
      coverJsonToHtml(selectId, msg.lists);
    }
  });
}

/** 把 JSON 陣列轉成 option 塞進 select */
function coverJsonToHtml(selectId, nodeArray){
  var tempSelect = $j("#" + selectId);
  isClearSelect(selectId, '0');
  for (var i = 0; i < nodeArray.length; i++){
    tempSelect.append($j('<option value="' + nodeArray[i].dm + '">' + nodeArray[i].mc + '</option>'));
  }
  getCpgjThgl(selectId, 'thgjDm');
}

/** 清空下拉列表(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;
  }
}

/** 依「引用軟體」的選項過濾「退化構件」清單 */
function getCpgjThgl(selectId1, selectId2){
  var obj1 = document.getElementById(selectId1);
  var obj2 = document.getElementById(selectId2);
  var len = obj1.options.length;
  if (len == 1) return false;
  obj2.length = 1; // 保留「無」這一項
  for (var i = 0; i < len; i++){
    if (i != obj1.selectedIndex){
      obj2.appendChild(obj1.options[i].cloneNode(true)); // 複製 option
    }
  }
}

對應的 HTML 結構相當直觀:一個文字框加隱藏欄位放「引用軟體」,一個 select 放「引用分版」,另一個 select 放「退化構件」,並在分版 select 的 onChange 中呼叫 getCpgjThgl('yyfbDm','thgjDm') 完成即時過濾。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved