AdSense

網頁

2018/2/12

使用JavaScript原生DOM function新增下拉選單內容

使用JavaScript原生DOM function新增select選單的option內容範例如下

<div>
  <select id="selectUser"></select>
</div>

<script>
$(document).ready(function(){
  // <option>的內容來源
  var data = [
              {"id":"1", "name":"Matt"},
              {"id":"2", "name":"Joey"},
              {"id":"3", "name":"Cara"}
             ];
             
  for (var i in data) {
    var user = data[i];
    var selectUser = document.getElementById("selectUser"); // 取得<select>
    var optionNode = document.createElement("OPTION");      // 建立<option>
    optionNode.setAttribute('value', user.id);              // 設定<option>的value屬性值
    optionNode.textContent = user.name;                     // 設定<option>的文字內容
    selectUser.appendChild(optionNode);                     // 將<option>設為<select>的子節點
  }   
 
});
</script>

結果如下

如果覺得文章有幫助的話還幫忙點個Google廣告,感恩。

沒有留言:

AdSense