我一直想有一個數組填充一個下拉里面,我得到了這個職位這方面的例子:JavaScript - populate drop down list with array的Javascript只有工作時HTML文檔
我使用這個網站:
<select id="selectNumber">
<option>Choose a number</option>
</select>
用這個js
var select = document.getElementById("selectNumber");
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
但是,如果我把HTML文檔裏面的JS它僅適用,如果我把它放在一個單獨的文件,它給了我這個errror在Chrome:
>Uncaught TypeError: Cannot read property 'appendChild' of null at g.js:8
我也tryed這一個,但同樣的事情發生:
var select = document.getElementById("selectNumber");
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.text = opt;
el.value = opt;
select.add(el);
}
的代碼只有當我把它放在HTML文件中工作,但如果我有它在一個單獨的文件,它給了我這個錯誤。
任何想法爲什麼?
總結你的代碼(https://developer.mozilla.org/en/docs/Web/Events/DOMContentLoaded)和引用的JS文件在後DOM元素 – Satpal
你用'jquery'標記了這個,但似乎沒有使用它? – trincot