当我试图使用数组推送将选择选项加载到optStored数组中时,该数组始终为空。在Chrome、Firefox和Safari中,代码正常工作,但在Internet Explorer中不起作用。有没有解决方法或者无法解决?
更新于10/11/16 2:12am: 对代码进行了一些更改,以前的代码已被注释掉,但数组仍然为空!是否有解决方案?
// 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>
add
方法?或者它有这个方法,但是参数不同(例如,使用字符串而不是<option>
标签)? - Greg Burghardtlength
属性来轻松地实现一个push
。这里还有一个:http://stackoverflow.com/q/31533963/2788872 - John Weisz