使用Javascript给出以下菜单http://jsfiddle.net/pYJPc/,我将如何遍历所有选项并逐个删除它们?然后重新添加它们。我不希望在所有
中删除选择菜单本身答案 0 :(得分:1)
以下是使用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将删除您选择标记中的所有选项:
//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,并将备份更改为:
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;
}
答案 1 :(得分:0)
您的HTML:
<select id="menu" onchange="go()">
<option>--Select a page--</option>
<option value="1">W3Schools</option>
<option value="2">Microsoft</option>
<option value="3">AltaVista</option>
</select>
<input id="remove" type="button" value="remove one" >
<input id="repop" type="button" value="repop">
你的JS与jQuery
var buffer=new Array();
$("#remove").click(function() {
buffer.push($("option:first").get(0));
$("option:first").remove();
});
$("#repop").click(function() {
$("select").append(buffer);
});
答案 2 :(得分:-1)
加载jQuery:
var options = $('#menu').children();
children.remove();
$('#menu').insert(children);
同样在不同的图书馆中也是如此。
没有库,你需要做更多的工作:)