js怎么把 select选中的多个选项左边移到右边
时间: 2023-12-05 18:04:25 浏览: 28
可以通过以下步骤实现将 select 中选中的多个选项从左边移到右边:
1. 获取 select 元素和左右两侧的容器元素。
2. 给 select 元素添加 change 事件监听器,当选中的选项发生变化时触发。
3. 在事件处理函数中,获取所有被选中的选项,将它们从左侧容器中移除,并添加到右侧容器中。
下面是一个示例代码:
HTML 代码:
```html
<select id="select" multiple>
<option value="1">选项1</option>
<option value="2">选项2</option>
<option value="3">选项3</option>
<option value="4">选项4</option>
<option value="5">选项5</option>
</select>
<div>
<div id="left-container">
<p>左侧容器</p>
</div>
<div id="right-container">
<p>右侧容器</p>
</div>
</div>
```
JavaScript 代码:
```js
const select = document.getElementById('select');
const leftContainer = document.getElementById('left-container');
const rightContainer = document.getElementById('right-container');
select.addEventListener('change', () => {
// 获取所有被选中的选项
const selectedOptions = Array.from(select.selectedOptions);
// 将选中的选项从左侧容器中移除,添加到右侧容器中
selectedOptions.forEach(option => {
leftContainer.removeChild(option);
rightContainer.appendChild(option);
});
});
```
在这个示例中,我们首先获取了 select 元素和左右两侧的容器元素,然后给 select 元素添加了 change 事件监听器,在事件处理函数中获取所有被选中的选项,将它们从左侧容器中移除,并添加到右侧容器中。