从 SELECT 菜单中删除然后重新添加选项元素? [英] Remove then Re-Add option elements from SELECT menu?

查看:25
本文介绍了从 SELECT 菜单中删除然后重新添加选项元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下菜单 http://jsfiddle.net/pYJPc/ 使用 Javascript,我将如何迭代通过所有选项并一一删除它们?然后将它们全部重新添加.我根本不想删除选择菜单本身

Given the following menu http://jsfiddle.net/pYJPc/ using Javascript, how would I iterate through all options and remove them one by one? then re-add them all. I don't want the select menu itself to be removed at all

推荐答案

这是使用 Vanilla JavaScript 的一种方法 JSFiddle 演示:

Here is one way to do it using Vanilla JavaScript JSFiddle Demo:

这是标记 HTML:

<select id="myselect">
    <option value='none'>--Select a page--</option>
    <option value="1">W3Schools</option>
    <option value="2">Microsoft</option>
    <option value="3">AltaVista</option>
</select>
<br/><br/>
<button value='add' id='addbtn' name='addbtn'>add</button>
<button value='delete' id='deletebtn' name='deletebtn'>delete</button>

使用 cloneNode 来备份您的默认选择选项.如果没有选项,addOption 会将备份添加回您的选择,deleteOption 将删除您选择标签中的所有选项:

Using cloneNode to backup your default select options. The addOption will add the backup back to your select if there is no options and the deleteOption will delete all options in your select tag:

//clone our options to a backup
var myselect = document.getElementById('myselect');
var backup = myselect.cloneNode(true).getElementsByTagName('option');
//add backup back into select
function addOption() {
    if (myselect.options.length == 0) {
        for (var i = 0; i < backup.length; i++) {
            myselect.options.add(backup[i].cloneNode(true));
        }
    }
}
//delete all option in select
function deleteOption() {
    while (myselect.options.length != 0) {
        myselect.options.remove(myselect.options.length - 1);
    }
}
//attach click event to btns
document.getElementById('addbtn').onclick = addOption;
document.getElementById('deletebtn').onclick = deleteOption;

在 IE 中,cloneNode 并没有真正克隆它.因此,我们必须创建自己的 cloneNode,并将备份更改为:

Turns out in IE cloneNode does not really clone it. So, we'll have to create our own cloneNode, and change the backup to:

var backup = IEcloneNode(myselect).getElementsByTagName('option');

//FOR IE 
//Reference http://brooknovak.wordpress.com/2009/08/23/ies-clonenode-doesnt-actually-clone/
function IEcloneNode(node) {
    // If the node is a text node, then re-create it rather than clone it
    var clone = node.nodeType == 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
    // Recurse
    var child = node.firstChild;
    while(child) {
        clone.appendChild(IEcloneNode(child));
        child = child.nextSibling;
    }

    return clone;
}

这篇关于从 SELECT 菜单中删除然后重新添加选项元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆