我有两个下拉列表,我使用以下方法将其清空:
document.getElementbyId("select1").options.length = 0;
当另一个改变时。如何使用 javascript 用旧值重新填充它?
我有两个下拉列表,我使用以下方法将其清空:
document.getElementbyId("select1").options.length = 0;
当另一个改变时。如何使用 javascript 用旧值重新填充它?
您可以通过在innerHTML
将其清除之前将其保存到变量来实现这一点,如下所示:
纯Javascript
<script>
// Save it
var old_options = document.getElementbyId("select1").innerHTML;
// Clear it
document.getElementbyId("select1").options.length = 0;
// Refill it
document.getElementbyId("select1").innerHTML = old_options;
</script>
如果它对您可用,那么我强烈推荐 jQuery。
jQuery版本
<script>
// Save it
var old_options = $('#select1').html();
// Clear it
$('#select1').html('');
// Refill it
$('#select1').html(old_options);
</script>
在清空之前克隆您的原始选择:
var mySelect=document.getElementById("select1");
var savedSelect=mySelect.cloneNode(true);
稍后,您可以将 savedSelect 选项推回原始选择,例如使用循环:
for (var i=0;i<savedSelect.options.length;i++) {
mySelect.appendChild(savedSelect.options[i].cloneNode(true));
}
还有其他复制选项,例如使用文档片段。请注意,innerHTML 不适用于 IE 中的选择元素。