<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>select.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body>
<select id="firstselect" size="10" multiple="multiple">
<option>选项1</option>
<option>选项2</option>
<option>选项3</option>
<option>选项4</option>
<option>选项5</option>
<option>选项6</option>
<option>选项7</option>
<option>选项8</option>
</select>
<button id="add" name="add">add</button>
<button id="addall" name="addall">addall</button>
<select id="secondselect" size="10" multiple="multiple">
<option>选项9</option>
</select>
<script type="text/javascript">
//获取按钮 注册事件
document.getElementById("add").onclick = function() {
//获取左边的select结点
var firstselect = document.getElementById("firstselect");
//获取右边的select结点
var secondselect = document.getElementById("secondselect");
//获取firstselect中的option结点,并得到其长度
var optionElements = firstselect.getElementsByTagName("option");
var len = optionElements.length;
//获取选中的option结点
//1.用select的 .selectedIndex属性来获取第一个被选中的索引
//测试是否可用 alert(firstselect.selectedIndex);
//2.移动,先将索引的第一个移过去,必须遍历所有的结点,至少8次
for ( var i = 0; i < len; i++) {
if (firstselect.selectedIndex != -1) {
secondselect
.appendChild(optionElements[firstselect.selectedIndex]);
}
}
}
//addall按钮方法一
/*
document.getElementById("addall").onclick = function() {
//获取左边的select结点
var firstselect = document.getElementById("firstselect");
//获取右边的select结点
var secondselect = document.getElementById("secondselect");
//获取firstselect中的option结点,并得到其长度
var optionElements = firstselect.getElementsByTagName("option");
var len = optionElements.length;
while ( len!=0) {
var optionElement=optionElements[0];
secondselect.appendChild(optionElement);
}
}
*/
//addalla按钮方法二
document.getElementById("addall").onclick = function() {
//获取左边的select结点
var firstselect = document.getElementById("firstselect");
//获取右边的select结点
var secondselect = document.getElementById("secondselect");
var len =firstselect.length;
for(var i=0;i<len;i++){
secondselect.appendChild(firstselect[0]);
}
}
//双击添加
document.getElementById("firstselect").ondblclick = function() {
alert("runned");
//获取左边的select结点
var firstselect = document.getElementById("firstselect");
//获取右边的select结点
var secondselect = document.getElementById("secondselect");
var optionElements=document.getElementsByTagName("option");
var len =optionElements.length;
for(var i=0;i<len;i++){
secondselect.appendChild(optionElements[firstselect.selectedIndex]);
}
}
</script>
</body>
</html>