function populateList(givenID)//givenID from the select tag
{
var select = document.getElementById("givenID"),
listData = ["1","2"];
for(var i = 0; i < listData.length; i++)
//Loops through array and creates a new DOM node and appends array contents to the object
{
var option = document.createElement("OPTION"),
txt = document.createTextNode(listData[i]);
option.appendChild(txt);
option.setAttribute("value",listData[i]);
select.insertBefore(option,select.lastChild);
}
}
<body >
<select id="slt" whenpageloads="populateList">
<!--When the page loads the select tag will be populated -->
<option>
default
</option>
</select>
</body>
答案 0 :(得分:0)
您可以像阿伦在身体负荷中提到的那样调用onload。
<body onload="populateList('slt')">
或
如果要加载多个选择框,这将是更好的选择。
window.onload = function() {
populateList('slt');
};
此外,由于给定ID是可变的,因此您的代码中还有另外一个错误。
var select = document.getElementById(givenID);
代替
var select = document.getElementById("givenID");
function populateList(givenID)//givenID from the select tag
{
var select = document.getElementById(givenID);
listData = ["1","2"];
for(var i = 0; i < listData.length; i++)
{
var option = document.createElement("OPTION"),
txt = document.createTextNode(listData[i]);
option.appendChild(txt);
option.setAttribute("value",listData[i]);
select.insertBefore(option, select.lastChild);
}
}
window.onload = function() {
populateList('slt');
};
<body>
<select id="slt">
<option>
default
</option>
</select>
</body>