首页 > 解决方案 > 复制突出显示的元素 谁能告诉我,如何使用 JavaScript(不是 jQuery)在单击按钮时将突出显示/选定的选项元素从一个选择标签复制到另一个选择?select 标记具有 size 属性,因此它不是下拉列表。函数 copy_all() { var roleList = document.getElementById("roles"); var asgned_roles = document.getElementById("asgndroles"); asgned_roles.inne

问题描述

标签: javascripthtml-select

解决方案


要获取index所选option元素的 ,请使用该selectedIndex属性。

要将选项附加到目标,请select使用该appendChild()方法。

要从源中删除选项,请select使用该removeChild()方法。

var source_select = document.getElementById("roles");
var target_select = document.getElementById("asgndroles");

function copy_selected() {
  var selected_option = source_select.options[source_select.selectedIndex];
  source_select.removeChild(selected_option);
  target_select.appendChild(selected_option);
}
<select size="5" id="roles">
  <option>Admin</option>
  <option>User</option>
  <option>Super User</option>
  <option>Super Admin</option>
</select>
<select size="5" id="asgndroles">
</select>
<button onclick="copy_selected()">COPY</button>


推荐阅读