【问题标题】:Style Option in Selectbox using Javascript使用 Javascript 选择框中的样式选项
【发布时间】:2012-10-11 16:20:32
【问题描述】:

我需要你的帮助。

我正在使用下面的代码向选择框动态添加选项。但是,如何使用 javascript 在选择框中为每个选项添加样式?并动态执行?

var status = new Array()
status[0] = ""
status[1] = "ACTIVE"
status[2] = "ON HOLD"
status[3] = "CLOSED"
for (i=0; i<status.length; i++) { document.getElementById('status').options[i]=new Option(status[i], i) }

即) [下拉式菜单] ACTIVE(文本颜色为绿色) ON HOLD(文字颜色为黄色) CLOSED(文字颜色为红色)

感谢您的所有帮助和支持。

干杯,

【问题讨论】:

    标签: javascript html dom


    【解决方案1】:

    您可以为每个元素单独设置样式,也可以预先设置 css 类并将类名分配给元素。

    查看这个 stackoverflow 问题: Style Option in Selectbox using Javascript

    看看这个小提琴: http://jsfiddle.net/xdXFz/

    (可选)see how to dynamically create select with options

    示例:

    var statuses = ["", "ACTIVE", "ON HOLD", "CLOSED"];
    var elSelect = document.getElementById("status");
    
    for ( var i = 0; i < statuses.length; i++ ){
    
        var elOption = document.createElement("option");
            // ex: Assign a css class to the option
            elOption.setAttribute('class', 'Your_CSS_Classname_Here');
            
            // ex: style the option
            elOption.style.fontWeight = 'bold';
            
            // set the value of the option
            elOption.setAttribute("value", statuses[i]);
            
            // set the text that displays for the option
            elOption.innerHTML = statuses[i];
        
        // add the option to your select dropdown
        elSelect.appendChild(elOption);
    
    }
    

    【讨论】:

    • 您的第一个链接是您回答的这个问题。这是故意的吗?
    【解决方案2】:

    可能是这样的:

    var status = new Array()
    status[0] = ""
    status[1] = "ACTIVE" 
    status[2] = "ON HOLD" 
    status[3] = "CLOSED"
    
    var s1 = status[1];
    var s2 = status[2];
    var s3 = status[3];
    
    if (s1) {
      //style here
    }
    else if (s2) {
      //style here
    }
    else if (s3) {
      //style here
    }
    
    for (i=0; i<status.length; i++) { document.getElementById('status').options[i]=new Option(status[i], i) } 
    

    几乎没有经过测试或改进。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-01
      • 2011-06-14
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多