<html>
<head>
<script>
function addfruits()
{
for(i = 0; i < document.getElementById("fruits").options.length; i++)
{
if(document.getElementById("fruits").options[i].selected)
{
var fruitslist = document.getElementById("fruitslist");
var option = document.createElement("option");
option.text = document.getElementById("fruits").options[i].text;
fruitslist.add(option);
}
}
}
</script>
</head>
<body>
<select id="fruits" name="fruits[]" multiple>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pear">Pear</option>
<option value="grape">Grape</option>
</select>
<input type="submit" name="submit" value=">>" onclick="addfruits()" />
<select id="fruitslist" name="fruitslist[]" style="width: 70px;" multiple>
</select>
</body>
</html>
从上面的代码中,首先我从下拉列表中选择Orange,然后点击&gt;&gt;按钮,橙色值将添加到fruitslist下拉列表中。
之后。我从下拉列表中再次选择橙色,然后点击&gt;&gt;按钮,橙色值将再次添加到fruitslist下拉列表中。
但是,我只想在fruitslist下拉列表中添加一次Orange值。
我应该如何修改它?有人能帮助我吗?
答案 0 :(得分:1)
尝试将addFruits
功能更改为以下内容:
function addfruits()
{
for (var i = 0; i < document.getElementById("fruits").options.length; i++)
{
if (document.getElementById("fruits").options[i].selected)
{
var optionText = document.getElementById("fruits").options[i].text;
var fruitslist = document.getElementById("fruitslist");
var found = false;
//Does the item clicked on already exist in the destination list?
for (var j = 0; j < fruitslist.length; j++) {
if (fruitslist[j].text == optionText) {
found = true;
break;
}
}
//If the item does not exist, add it to the list.
if (!found) {
var option = document.createElement("option");
option.text = optionText;
fruitslist.add(option);
}
}
}
}
这里要做的重要事情是首先检查fruitslist
是否包含被点击的项目,因此需要额外的for循环。
答案 1 :(得分:1)
这是修复。
<html>
<head>
<script>
function addfruits()
{
for(i = 0; i < document.getElementById("fruits").options.length; i++)
{
if(document.getElementById("fruits").options[i].selected && !isAddedAlready(document.getElementById("fruits").options[i].text))
{
var fruitslist = document.getElementById("fruitslist");
var option = document.createElement("option");
option.text = document.getElementById("fruits").options[i].text;
fruitslist.add(option);
}
}
}
function isAddedAlready(text) {
var fruitslist = document.getElementById("fruitslist");
if(fruitslist.length ==0) return false;
for(var i=0; i<fruitslist.length; i++) {
if(fruitslist.options[i].text === text) return true;
}
return false;
}
</script>
</head>
<body>
<select id="fruits" name="fruits[]" multiple>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pear">Pear</option>
<option value="grape">Grape</option>
</select>
<input type="submit" name="submit" value=">>" onclick="addfruits()" />
<select id="fruitslist" name="fruitslist[]" style="width: 70px;" multiple>
</select>
</body>
</html>