【发布时间】:2021-10-08 21:03:10
【问题描述】:
在数组中添加 createElements - 文本和值,而不需要 forLoop。
尝试了 map、forEach,但在内存方面...它仍然滞后于大量条目。
请帮忙。
templateList example: ["a", "b", "c", "d", "e", "f"];
var templateList = new Array();
var selection = document.getElementsByName("name")[0];
for(var i = 0; i < templateList.length; i++) {
var open = document.createElement("Option");
open.text = templateList[i];
open.value = templateList[i];
selection.add(open);
}
【问题讨论】:
-
到底是什么问题?
templateList是否已经包含值?给定您的templateList数组,代码可以缩短为const selection = document.querySelector(".name"); templateList.forEach((value) => selection.add(new Option(value, value)));。见Option。 -
是的,它们是字符串。问题是 for 循环必须一遍又一遍地迭代。想要尝试找到一种不必这样做的方法......它正在迭代模板列表数组中的太多变量。
-
为什么它必须一遍又一遍地迭代值(而不是变量)?
-
我想把 selection.add 放到循环之外并在循环之后添加一个节点列表可以提高绘图性能
-
它是如何显示的......它是一个下拉框。
标签: javascript html ecmascript-5 createelement