<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>无标题页</title>
<script language="javascript" type="text/javascript"> //移动选中项
function moveSelectedItem(selectSource,selectTarget) {
for (var i = 0; i < selectSource.options.length; i++) {
if (selectSource.options[i].selected)
{
selectTarget.appendChild(selectSource.options[i]);
}
}
selectSource.selectedIndex = -1;
selectTarget.selectedIndex = -1;
} //左移动到右
function moveToRight() {
var selectLeftObj = document.getElementById("selectLeft");
var selectRightObj = document.getElementById("selectRight");
moveSelectedItem(selectLeftObj, selectRightObj);
}
</script>
</head>
<body>
<table id="tableContent" border="1" style="background-color:Fuchsia">
<tr>
<td>
<select id="selectLeft" multiple="multiple" style="height:120px; width:100px">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
<option value="F">F</option>
</select>
</td>
<td>
<input type="button" value=">" style="width:50px; height:20px" onclick="moveToRight();" /><br /> </td>
<td>
<select id="selectRight" multiple="multiple" style="height:120px;width:100px"></select>
</td>
</tr>
</table>
</body>
</html>最近弄个左右选择框,就是左边的选中,添加到右边,可是发现了个问题moveSelectedItem 方法中,
for (var i = 0; i < selectSource.options.length; i++) {
if (selectSource.options[i].selected)
{
selectTarget.appendChild(selectSource.options[i]);
}
}
这段代码 添加到目标控件的时候,项会减少,但我遍历了左边的控件,发现都能打印出来,但一添加到别的select控件就会出现减少,这是什么原因呢?请大家看下,多谢!在线等!
//复制选中项
function copeSelectedItem(selectSource,selectTarget) {
for (var i = 0; i < selectSource.options.length; i++) {
if (selectSource.options[i].selected)
{
selectTarget.add(new Option(selectSource.options[i].value,selectSource.options[i].text));
}
}
selectSource.selectedIndex = -1;
selectTarget.selectedIndex = -1;
}
原理是什么呢?
function moveSelectedItem(selectSource,selectTarget) {
for (var i = 0; i < selectSource.options.length; i++) {
if (selectSource.options[i].selected)
{
if(selectTarget.options.length!=0)
{
for(var j=0;j<selectTarget.options.length;j++)
{
if(selectSource.options[i].text!=selectTarget.options[j].text)
{
selectTarget.add(new Option(selectSource.options[i].value,selectSource.options[i].text));
}
}
}
else
{
selectTarget.add(new Option(selectSource.options[i].value,selectSource.options[i].text));
}
}
}
selectSource.selectedIndex = -1;
selectTarget.selectedIndex = -1;
}