列表选项javascript和双击的问题



我做了两个选择,当我按下一个选择时,我希望数据被转移到另一个,并从原来的一个中删除。反之亦然在某一时刻,我的值1被删除,只剩下2

下面是我测试的代码这是我的问题还是一个正常的错误

const insertList = (list) => {
if (list === 1) {
let selectOne = document.getElementById("list_one");
let selectTwo = document.getElementById("list_two");
let option = document.createElement("option");
console.log(selectOne.value)
option.text = selectOne.value;
selectTwo.add(option);
selectOne.remove(option);
} else if (list === 2) {
let selectTwo = document.getElementById("list_two");
let selectOne = document.getElementById("list_one");
let option = document.createElement("option");
console.log(selectTwo.value)
option.text = selectTwo.value;
selectOne.add(option);
selectTwo.remove(option);
}
}
document.getElementById('list_one').ondblclick = () => {
insertList(1);
};
document.getElementById('list_two').ondblclick = () => {
insertList(2);
};
<label for="list_one">List 1</label>
<select name="list_one" id="list_one" multiple size="3">
<option value="1">1</option>
</select>
<br><br>
<label for="list_two">List 2</label>
<select name="list_two" id="list_two" multiple size="3">
<option value="2">2</option>
</select>

  1. 您要查找的是textContent
  2. 您可以通过委派来简化代码,使其更DRY一些。

document.getElementById("container").addEventListener("dblclick", function(e) { 
const tgt = e.target.closest("label");
if (!tgt) return; // we did not click a select
let option = document.createElement("option");
const listA = tgt.querySelector("select"); // clicked select
const sibling = tgt.nextElementSibling || tgt.previousElementSibling; // the other sibling
const listB = sibling.querySelector("select");
option.textContent = listA.options[listA.selectedIndex].textContent; // get the text
option.value = listA.value; // get the value
option.selected=true; // set the option to selected to focus it when copying
listB.add(option);
listA.remove(option);
})
label { margin-bottom: 5px; display: block }
select { width:50px}
<div id="container">
<label>List 1
<select name="list_one" id="list_one" multiple size="3">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</label>
<label>List 2
<select name="list_two" id="list_two" multiple size="3">
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
</select>
</label>
</div>