Javascript - 选项api添加方法不添加到第二个元素

时间:2018-05-21 21:59:36

标签: javascript

我不确定是否错过理解Option api

问题:Option元素的.add方法,不会添加到第二个元素。

代码示例

var year = getElement('#by_year'),
year_download = getElement('#download_by_year');

//data.years (just stores the year in a string format)[2018]

//the following will only store in the first option
data.years.forEach(function(y){
    let opt = document.createElement("option");
    let currentTime = new Date();
    opt.value = y.year;
    opt.text = y.year;
    if (currentTime.getFullYear() == y.year){opt.defaultSelected = true;}
    year.add(opt, null);//first select box
    year_download.add(opt, null); // second select box
});
//I solved it like this, but it's redundant
data.years.forEach(function(y){
    let opt = document.createElement("option");
    let currentTime = new Date();
    opt.value = y.year;
    opt.text = y.year;
    if (currentTime.getFullYear() == y.year){opt.defaultSelected = true;}
    year.add(opt, null);
});
data.years.forEach(function(y){
    let opt = document.createElement("option");
    let currentTime = new Date();
    opt.value = y.year;
    opt.text = y.year;
    if (currentTime.getFullYear() == y.year){opt.defaultSelected = true;}
    year_download.add(opt, null);
});

问题:为什么它只将选项添加到一个而不是两个?

1 个答案:

答案 0 :(得分:0)

DOM元素被设计为具体对象,只能“附加”到DOM树中的一个位置。它们不像可以添加到多个父项以创建文档的多个段的抽象模型。您需要为每个选择使用不同的选项元素。您可以使用函数来减少冗余:

function addYearOption(select, year) {
  let opt = document.createElement("option");
  let currentTime = new Date();
  opt.value = y.year;
  opt.text = y.year;
  if (currentTime.getFullYear() == y.year){opt.defaultSelected = true;}
  select.add(opt, null);
}

data.years.forEach(function(y){
  addYearOption(year, y);
  addYearOption(year_download, y);
});