英文:
An Array inserted via Html tag does not give me the same vlist in multiple cells
问题
只有使用 document.getElementById
才能使第一个单元格正常工作。
var select = document.querySelector("select");
var options = ["Kurs1", "Kurs2", "Kurs3", "Kurs4", "Kurs5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var kurse = document.createElement("option");
kurse.textContent = opt;
kurse.value = opt;
select.appendChild(kurse);
}
显然,不能使用相同的 id 或类名,我尝试过使用标签名称等等,都没有成功。我在 JavaScript 方面刚刚开始,希望您能帮助我理解为什么,谢谢。
英文:
Problem code that takes a single array and through the select command of the html it calls me in more cells of the same list, but I tried all the getElement or query, as you can see, only the first cell goes.
Only entering the document.getElementById does the first cell work.
<select id="ku">
<option>Choose a number</option>
</select>
<select id="ku">
<option>Choose a number</option>
</select>
<select id="ku">
<option>Choose a number</option>
</select>
<script>
var select = document.querySelector("select");
var options = ["kurs1", "Kurs2", "Kurs3", "Kurs4", "Kurs5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var kurse = document.createElement("option");
kurse.textContent = opt;
kurse.value = opt;
select.appendChild(kurse);
}
</script>
Obviously the ids or classes cannot be entered the same, I tried to enter the tag name etc... nothing.
I'm desperate and just starting out with JS. I hope you can help me understand why, thank you.
答案1
得分: 0
使用类而不是重复的 id。 document.querySelectorAll
可以用来获取与选择器匹配的所有元素。
const options = ["Kurs1", "Kurs2", "Kurs3", "Kurs4", "Kurs5"];
const selects = document.querySelectorAll('select.ku');
for (const option of options)
for (const select of selects)
select.add(new Option(option));
<select class="ku">
<option>选择一个数字</option>
</select>
<select class="ku">
<option>选择一个数字</option>
</select>
<select class="ku">
<option>选择一个数字</option>
</select>
英文:
Use a class instead of duplicating ids. document.querySelectorAll
can be used to obtain all elements matching a selector.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const options = ["kurs1", "Kurs2", "Kurs3", "Kurs4", "Kurs5"],
selects = document.querySelectorAll('select.ku');
for (const option of options)
for (const select of selects)
select.add(new Option(option));
<!-- language: lang-html -->
<select class="ku">
<option>Choose a number</option>
</select>
<select class="ku">
<option>Choose a number</option>
</select>
<select class="ku">
<option>Choose a number</option>
</select>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论