我正在尝试将select {1中的选定选项移动到按钮click
上的select2中。这是我的HTML代码:
<p>
<select id="select1" size="10" style="width: 25%" multiple>
<option value="purple">Purple</option>
<option value="black">Black</option>
<option value="orange">Orange</option>
<option value="pink">Pink</option>
<option value="grey">Grey</option>
</select>
</p>
<button type="button" click.delegate="trig()">Add</button>
<p>
<select id="select2" size="10" style="width: 25%" multiple>
<option value="white">White</option>
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
</p>
这是我的包含按钮的JS代码
export class App {
constructor() {
}
trig() {
}
}
我需要在trig()
中添加什么,以便在单击该按钮时将选定的项目移到另一个列表?
答案 0 :(得分:3)
答案 1 :(得分:3)
您可以遍历selectedColors1
并获取每个选定项目的index
。然后将它们推入color2
数组,并将它们从colors
数组中一个接一个地删除。
演示:CodeSandbox
export class App {
colors1 = [
{ id: "purple", name: "Purple" },
{ id: "black", name: "Black" },
{ id: "orange", name: "Orange" }
];
colors2 = [
{ id: "white", name: "White" },
{ id: "red", name: "Red" },
{ id: "blue", name: "Blue" }
];
selectedColors1 = [];
selectedColors2 = [];
add() {
this.selectedColors1.forEach(selected => {
// get the index of selected item
const index = this.colors1.findIndex(c => c.id === selected);
this.colors2.push(this.colors1[index]); // add the object to colors2
this.colors1.splice(index, 1); // remove from colors1
});
}
}
HTML:
<select multiple value.bind="selectedColors1">
<option repeat.for="color of colors1" model.bind="color.id">
${color.name}
</option>
</select>
<button type="button" click.delegate="add()">Add</button> <br />
<select multiple value.bind="selectedColors2">
<option repeat.for="color of colors2" model.bind="color.id">
${color.name}
</option>
</select>