我知道关于此主题的文章很多,因此我已经关注了他们。但是,我似乎无法使下拉列表填充我的选项。也许我凝视它已经太久了……任何帮助都将受到赞赏。
var fromYear = document.getElementById("from-year");
var toYear = document.getElementById("to-Year");
var years = ["2019","2020","2021","2022","2023","2024","2025","2026"];
for(var i = 0; i < years.length; i++) {
var opt = years[i];
var el = document.createElement("year");
el.textContent = opt;
el.value = opt;
fromYear.appendChild(el);
toYear.appendChild(el);
}
<div>
<div class = "date-from">
<select id="from-year">
<option>from: Year</option>
</select>
</div>
<div class = "date-to">
<select id="to-year">
<option>to: Year</option>
</select>
</div>
</div>
{% load static %}
<script src="{% static 'buildstats/buildStats.js' %}"></script>
我在此.js文件中还有其他JavaScript,它可以正常工作并在DOM上填充元素。只是此选项列表不需要填充。选项列表中唯一填充的项目是我在HTML文档中为其赋予的默认值。
答案 0 :(得分:1)
您使用let x: Result<Int?> = .nil
XCTAssertNil(x.resolve())
的ID错误。没有可以创建的名为year的元素,而是将选项放在createelement中。而且您不能将一个元素附加到多个选择中。您必须创建单独的元素,然后将两者都添加到各自的选择中
to-year
var fromYear = document.getElementById("from-year");
var toYear = document.getElementById("to-year");
var years = ["2019","2020","2021","2022","2023","2024","2025","2026"];
for(var i = 0; i < years.length; i++) {
var opt = years[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
var el1 = document.createElement("option");
el1.textContent = opt;
el1.value = opt;
fromYear.appendChild(el);
toYear.appendChild(el1);
}
答案 1 :(得分:1)
var el = document.createElement(“ year”)不是一个选项,因为您正在使用select元素,因此应使用:
var el = document.createElement("option");
此外,您还可以通过 document.getElementById(“ to-Year”)获取该元素,那里有一个错字,因为您的元素ID为 to-year (小写)。
这应该做到:
var fromYear = document.getElementById("from-year");
var toYear = document.getElementById("to-year");
var years = ["2019","2020","2021","2022","2023","2024","2025","2026"];
for(var i = 0; i < years.length; i++) {
var elfrom = document.createElement("option");
var elto = document.createElement("option");
elfrom.text = years[i];
elfrom.value = years[i];
elto.text = years[i];
elto.value = years[i];
fromYear.appendChild(elfrom);
toYear.appendChild(elto);
}
<div>
<div class = "date-from">
<select id="from-year">
<option>from: Year</option>
</select>
</div>
<div class = "date-to">
<select id="to-year">
<option>to: Year</option>
</select>
</div>
</div>
答案 2 :(得分:1)
const fromYear = document.getElementById("from-year");
const toYear = document.getElementById("to-year");
const years = ["2019","2020","2021","2022","2023","2024","2025","2026"];
years.forEach(year => {
fromYear.append(new Option(year, year));
toYear.append(new Option(year, year));
});
<div>
<div class = "date-from">
<select id="from-year">
<option>from: Year</option>
</select>
</div>
<div class = "date-to">
<select id="to-year">
<option>to: Year</option>
</select>
</div>
</div>