默认情况下,我需要在组合框中显示文本“选择一个”

I need to display the text "Select the one" in the combo box by default

本文关键字:选择 选择一个 一个 文本 显示 情况下 组合 默认      更新时间:2023-09-26

我正在创建一个从 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循环之前使用所需的文本创建option

var option = document.createElement("option");
option.innerHTML = "Select the one";
document.form1.fruits.appendChild(option);

如果 option 不是select的第一个子项(即由于某种原因您没有将其放在 for 循环之前),则还要设置 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);
    }
}

尝试在 for 循环之前放置这样的东西:

var option = document.createElement("option");    
option.innerHTML = "Select One";
document.form1.fruits.appendChild(option);

我也可以强烈推荐jQuery来做这些恶作剧。

这里有一个非常相似的问题和答案:

HTML选择:如何设置下拉列表中不会显示的默认文本?

basically do this:
var option = document.createElement("option");
option.innerHTML = "Select the one";
option.setAttribute("selected", "selected");
option.setAttribute("disabled", "disabled");
document.form1.fruits.appendChild(option);

我想如果你真的想彻底,你可以添加一些东西,在菜单出现时隐藏此选项。