【问题标题】:jQuery - Is it possible to change selectbox's options during cloning?jQuery - 克隆期间是否可以更改选择框的选项?
【发布时间】:2018-03-11 08:59:37
【问题描述】:

克隆期间是否可以更改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>

【问题讨论】:

  • 是的,这是可能的,但是你的问题不是很清楚
  • 关于如何做到这一点的任何提示? (生病编辑问题)
  • jQuery 和你的问题之间有什么联系?我在这里看不到 jQuery
  • 难道不是通过使用 jQuery 我就能完成我的要求吗? @阿波罗
  • @noel293 jQuery 是一个 javascript 促进者,你可以用 jQuery 做的一切,你也可以用纯 JS 做

标签: javascript jquery html clone


【解决方案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;
<button id="btn_new_service">clone</button>

<div id="divToInsertInto">
</div>

【讨论】:

  • 不,脚本会克隆所有内容!我需要的是所选值不会出现在下一个克隆的选择框上
  • 当你运行我的代码 sn-p 时,选择一个值然后克隆,你是否也克隆了选定的值?因为我没有
  • 我可以在所有框中选择 c_service
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-07
  • 1970-01-01
  • 2011-01-08
  • 2010-10-19
  • 1970-01-01
相关资源
最近更新 更多