DIV CSS 佈局教程網

JS 取得下拉選單選中項目的「文字」而非值
編輯:JavaScript綜合知識     

select 的 value 是給程式用的代碼,使用者看到的卻是 option 的文字。當你需要把「上海」這個名稱存起來,而不是「2」這個值,就得換個方式取值。

HTML 結構

<select onchange="isSelected(this.value);" id="city">
 <option value="1">北京</option>
 <option value="2" >上海</option>
 <option value="3" >廣州</option>
</select>

寫法一:迴圈找出被選中的項目

function isSelected(value) {
 var cityName;
 var city = document.getElementById("city");
 for(i=0;i<city.length;i++){
  if(city[i].selected==true){
   cityName = city[i].innerText;
   alert("cityName:" + cityName);
  }
}

寫法二:直接用 selectedIndex

function isSelected(value) {
 var city = document.getElementById("city");
 alert(city.options[city.selectedIndex].innerText);
}

顯然簡潔得多,也不必跑迴圈。

關鍵:innerText 在 Firefox 無效

作者實測發現,city[i].innerText 在 IE 下正常,在 Firefox 卻拿不到值。原因是 innerText 原本是 IE 的私有實作,Firefox 長期不支援(直到 2016 年的 Firefox 45 才加入)。把 innerText 改成 text 就能同時在兩邊work:

alert(city.options[city.selectedIndex].text);

text 是 HTMLOptionElement 的標準屬性,等同於 textContent,跨瀏覽器都支援,也是取值時的首選。

innerText、textContent、text 怎麼選

  • option.text:option 專屬,最貼近這個需求,直接用。
  • textContent:所有節點通用的標準屬性,取得原始文字(包含隱藏元素、保留空白)。
  • innerText:會回傳「渲染後」的可見文字,受 CSS 影響、且會觸發 reflow 效能較差。除非你需要模擬使用者複製的行為,否則不必用。

更簡短的現代寫法

const city = document.getElementById('city');
const name = city.options[city.selectedIndex].text;

用 jQuery:

var name = $('#city option:selected').text();

記得同時保留 value 與 text 的用途區分:value 送給後端做查詢或儲存,text 只負責顯示。若兩者都需要,一次取出即可:

const opt = city.options[city.selectedIndex];
console.log(opt.value, opt.text);

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