4

当我尝试使用数组推送将选择选项加载到optStored数组中时,该数组始终保持为空。在 chrome、firefox 和 safari 中,代码可以正常工作,但在 Internet Explorer 中却不行。是否有解决此问题的方法或对此无能为力?

2016 年 10 月 11 日凌晨 2:12 更新:对代码进行了一些更改,之前的代码已被注释掉,但数组仍然为空!有解决办法吗?

// array to store select options
var optStored = [];

// filter select 
function filterFruits(el) {
  var value = el.value.toLowerCase();
  var form = el.form;
  var opt, sel = form.fruits;
  if (value == "") {
    restoreOpts();
  } else {
    for (var i = sel.options.length - 1; i >= 0; i--) {
      opt = sel.options[i];
      if (opt.text.toLowerCase().indexOf(value) == -1) {
        sel.removeChild(opt);
      }
    }
  }
}

// Restore select options
function restoreOpts() {
  var sel = document.getElementById('fruits');
  sel.options.length = 0;
  for (var i = 0, iLen = optStored.length; i < iLen; i++) {
    // Recent Update 2:12am 10/11/16:
    // Found aworkaround for restoring the select options 
    // This method works with versions of IE4+
    sel.options[sel.options.length] = new Option(optStored[i].text, optStored[i].value, false, false);

    // Recent Comment Update 2:12am 10/11/16: 
    // Console complains of a type mismatch error
    // sel.add(optStored[i], null); 
  }
}

// Load select options
window.onload = function() {
  var sel = document.getElementById('fruits');
  for (var i = 0, iLen = sel.options.length; i < iLen; i++) {
    // Recent Comment Update 2:12am 10/11/16: 
    // tried this method as well but no luck. 
    // it was also mentioned in the comments below
    // the array still remains empty!
    optStored[i] = sel.options[i];

    //optStored.push(sel.options[i]);
  }
};
<form>
  <input type="text" onkeyup="filterFruits(this);" placeholder="Filter">
  <select id="fruits">
    <option value="1">Apple</option>
    <option value="2">Orange</option>
    <option value="3">Cherry</option>
    <option value="4">Banana</option>
  </select>
</form>

4

2 回答 2

3

根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push#Browser_compatibility,IEpush仅从 5.5 版开始支持该方法。请尝试以下操作:

window.onload = function() {
  var sel = document.getElementById('fruits');
  for (var i = 0, iLen = sel.options.length; i < iLen; i++) {
    optStored[i] = sel.options[i];
  }
};
于 2016-10-11T02:25:10.413 回答
1

如果您按 F12,它会在控制台中显示任何错误吗?IE 控制台远不及 Chrome/Firefox 开发工具,但它应该显示任何错误。

我想知道undefined作为方法的第二个参数传递add,根据文档,它应该null将新选项附加到列表的末尾

before 是可选的,集合的一个元素,或者一个 long 类型的索引,表示项目 item 应该被插入到之前。如果此参数为 null(或索引不存在),则将新元素附加到集合的末尾。

https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/add

于 2016-10-07T13:11:33.627 回答