【问题标题】:javascript code to create html select menu not populating in IE8用于创建 html 选择菜单的 javascript 代码未填充在 IE8 中
【发布时间】:2014-08-23 22:07:12
【问题描述】:

此代码适用于 IE10+ 和 Chrome,但我需要它适用于 IE8。

我认为它一直有效到我用评论标记的那一点,因为会生成一个下拉菜单并缩放到正确的大小,但它不会填充任何可供选择的选项。此外,IE8 调试器不会给出任何错误,只是无法正确执行。

create_menu("letter", "letters_select_menu", ["a","b","c"]);

function create_menu(div_id, sel_id, menu_options) {

    var myDiv = document.getElementById(div_id);

    // create select menu and size
    var selectList = document.createElement("select");
    selectList.setAttribute("id", sel_id);
    selectList.setAttribute("size", menu_options.length);
    myDiv.appendChild(selectList);

    // i think it works up until this point

    // populate the menu with the options from the array
    for (var i = 0; i < menu_options.length; i++) {
        var option = document.createElement("option");
        option.setAttribute("value", menu_options[i]);
        option.text = menu_options[i];
        selectList.appendChild(option);
    }
};

在 IE10 上我看到了这个:

在 IE8 上我看到了这个:

您能在第二个代码块中看到任何可能与 IE8 不兼容并导致问题的内容吗?我一直在注释掉没有结果的东西,因为它们和第一个块中使用的命令都是一样的。

提前感谢您的帮助。

【问题讨论】:

    标签: javascript html internet-explorer select internet-explorer-8


    【解决方案1】:

    使用选择的“添加”功能。

    var sel = document.createElement('select');
    
    var option = documeng.createElement('option');
    option.value = '1';
    option.text = 'Option 1';
    
    sel.add(option, null);
    

    【讨论】:

      【解决方案2】:

      我找到了答案。 option.text 在 IE8 或 IE9 中不起作用,所以我将其更改为 option.innerHTML,现在可以使用了。

      对于最终结果:

      function create_menu(div_id, sel_id, menu_options) {
      
          var myDiv = document.getElementById(div_id);
      
          // create select menu and size
          var selectList = document.createElement("select");
          selectList.setAttribute("id", sel_id);
          selectList.setAttribute("size", menu_options.length);
          myDiv.appendChild(selectList);
      
          // populate the menu with the options from the array
          for (var i = 0; i < menu_options.length; i++) {
              var option = document.createElement("option");
              option.setAttribute("value", menu_options[i]);
              option.innerHTML = menu_options[i];
              selectList.appendChild(option);
          }
      };
      

      【讨论】:

      • innerHTML 可能不安全 (xss)。
      • 是的。为此目的应该没问题,但是您是否推荐替代方案?
      • 使用 jQuery:$(option).text(menu_options[i]);
      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      • 2012-08-14
      • 2012-07-24
      • 1970-01-01
      • 2017-12-28
      相关资源
      最近更新 更多