是否可以在克隆过程中更改selectbox's
选项?
我正在用内心的孩子克隆一个div。每次克隆时,每个人都有不同的id。原始div包含一个选择框,从数据库中获取它的值。 我的问题是,是否可以修改克隆选择框的值,使它们不包含先前选择的值?关于如何做到这一点的任何提示?
我需要的是新创建的选择框不会包含先前选择的值。
示例如果在选择框1中我选择1(范围为1-10),那么值1将不会出现在其他选择框中
JS
<script>
document.getElementById('btn_new_service').onclick = duplicate;
var i =0;
function duplicate() {
var original = document.getElementById('duplicator');
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicator" + ++i; // there can only be one element with
var new_service_ID = 'c_service-'+i;
var new_vat_ID = 'vat-'+i;
var new_amount_ID = 'amount-'+i;
var new_vatamount_ID = 'vat_amount-'+i;
clone.querySelector('#c_service').setAttribute('id',new_service_ID);
clone.querySelector('#vat').setAttribute('id',new_vat_ID);
clone.querySelector('#amount').setAttribute('id',new_amount_ID);
clone.querySelector('#vat_amount').setAttribute('id',new_vatamount_ID);
original.parentNode.appendChild(clone);
};
</script>
答案 0 :(得分:1)
您应该跟踪所选内容并从头开始重新选择,这会更容易
const selectClass = "mySelect";
const options = [
{id: "c_service", name: "c_service"},
{id: "vat", name: "vat"},
{id: "amount", name: "amount"},
{id: "vat_amount", name: "vat_amount"}
];
var id = 0;
function addSelect() {
// Get selects
let selects = document.getElementsByClassName(selectClass);
// Get all selected values
let selectedOpts = [];
for (let select of selects) {
if (select.value != "") {
selectedOpts.push(select.value);
}
}
// Create the new select
let select = document.createElement("select");
select.setAttribute("class",selectClass);
select.appendChild(document.createElement("option"));
// Get available options
var avOpts = options.filter(o => selectedOpts.indexOf(o.id) == -1);
// Create the options
for (var option of avOpts) {
id++;
let o = document.createElement("option");
o.setAttribute("id", option.id + id);
o.innerHTML = option.name;
select.appendChild(o);
}
// Add the select to DOM
document.getElementById("divToInsertInto").appendChild(select);
}
// add the initial select
addSelect();
// Attach event
document.getElementById('btn_new_service').onclick = addSelect;
&#13;
<button id="btn_new_service">clone</button>
<div id="divToInsertInto">
</div>
&#13;