簡體   English   中英

如何綁定數組數據以選擇選項

[英]how to bind array data to select option

我有數組數據它稱為“provinsi”我在控制台上像普通數組一樣得到數組

這是我的代碼

 <select id="select">
      <option value="default">default</option>
 </select>
 <script>
        console.log(provinsi)
        var select = document.getElementById("select");

        for(var i = 0; i < provinsi.length; i++)
        {
            var option = document.createElement("option"),
                txt = document.createTextNode(provinsi[i]);
            option.appendChild(txt);
            option.setAttribute("value",provinsi[i]);
            select.insertBefore(option,select.lastChild);
        }
    </script>

但我得到了這樣的結果在此處輸入圖片說明

這是我的控制台“provinsi” 在此處輸入圖片說明 有什么建議嗎? 之前謝謝

我相信DOM尚未准備好。

嘗試將代碼放入IIFE中。

(function() {
    // the DOM will be available here

    console.log(provinsi)
    var select = document.getElementById("select");

    for(var i = 0; i < provinsi.length; i++)
    {
        var option = document.createElement("option"),
            txt = document.createTextNode(provinsi[i]);
        option.appendChild(txt);
        option.setAttribute("value",provinsi[i]);
        select.insertBefore(option,select.lastChild);
    }

})();

**只是為了澄清@karthick所提到的內容,請確保將腳本加載在body標簽的末尾。

我希望這能使編碼愉快:)注意:使用原始值更改省份數組

 $(document).ready(()=> { let provinces = ["test1", "test2", "test3", "test4" ] $.each(provinces, function(key,item) { $("#select").append(new Option(item, key)); }); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="select"> <option value="default">default</option> </select> 

運行腳本時,DOM可能尚未完成加載。 您應該在DOMContentLoaded上運行函數。

 <select id="select"> <option value="default">default</option> </select> <script> var provinsi = ["test1", "test2"]; document.addEventListener("DOMContentLoaded", function(event) { //DOM fully loaded and parsed var select = document.getElementById("select"); for(var i = 0; i < provinsi.length; i++) { var option = document.createElement("option"), txt = document.createTextNode(provinsi[i]); option.appendChild(txt); option.setAttribute("value",provinsi[i]); select.insertBefore(option,select.lastChild); } }); </script> <script> </script> 

您可以使用jquery each函數進行looping

Javascript代碼:

var makers = [
  {id: 1, name: 'Toyota'}, 
  {id: 2, name: 'Nissan'}, 
  {id: 3, name: 'Honda'}
]
    
$.each(makers, function (index, item) {
   $('#makers-listing').append(`<option value="${item.id}">${item.name}</option>`);
});

html代碼:

<select id="makers-listing">
    <option>Select Maker</option> <!-- This is default value -->
</select>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM