我正在创建一个组合框,它从 JSON 加载选项。它按预期加载菜单。但我需要默认在组合框中显示文本“选择一个”。我尝试过,但找不到解决方案。您能给我建议吗?我怎样才能实现它?
window.onload = function() {
var obj = JSON.parse(str);
for (var i=0; i < obj.MenuParentTabs.length; i++) {
var option = document.createElement("option");
option.innerHTML = obj.MenuParentTabs[i].parentTabName;
document.form1.fruits.appendChild(option);
}
}
最佳答案
您需要在 for
循环之前创建包含所需文本的选项
:
var option = document.createElement("option");
option.innerHTML = "Select the one";
document.form1.fruits.appendChild(option);
如果 option
不是 select
的第一个子级(即,对于某些情况,您没有将其放在 for
循环之前) Reason),同时设置 selected
属性:
option.setAttribute("selected", "selected");
帮助OP的完整代码:
window.onload = function() {
var obj = JSON.parse(str);
var option = document.createElement("option");
option.innerHTML = "Select the one";
option.setAttribute("selected", "selected");
document.form1.fruits.appendChild(option);
for (var i = 0; i < obj.MenuParentTabs.length; i++) {
option = document.createElement("option");
option.innerHTML = obj.MenuParentTabs[i].parentTabName;
document.form1.fruits.appendChild(option);
}
}
关于javascript - 我需要默认在组合框中显示文本 "Select the one",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14584254/