Javascript 如何在javascript中填充select元素的选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6601028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to populate the options of a select element in javascript
提问by samach
The code:
编码:
var newSelect=document.createElement('select');
index=0;
var optn = document.createElement("option");
//langArray is an array that contains different items..the size
//is not fixed for this array.
for(element in langArray)
{
//Now i want to assign each item in langArray to each option tag
//will it be sumthng like "optn.options[index]=new Option("Sports", "sportsvalue", true, false);
//optn.accept(langArray[0]);
index++;
}
I'm trying to get options populated by this way but its not coming all right as I don't know how to populate the options from an array in JS. Do I even have to use the loop or can I just assign the langArray to some property of select element and every thing will be up and running?
我正在尝试通过这种方式填充选项,但由于我不知道如何从 JS 中的数组填充选项,因此它不会很好。我什至必须使用循环还是我可以将 langArray 分配给 select 元素的某些属性,然后一切都会启动并运行?
回答by Ibu
You can create the option inside the loop;
您可以在循环内创建选项;
for(element in langArray)
{
var opt = document.createElement("option");
opt.value= index;
opt.innerHTML = element; // whatever property it has
// then append it to the select element
newSelect.appendChild(opt);
index++;
}
// then append the select to an element in the dom
回答by James Long
You need to create your option
element inside your loop, set attributes and text and append it to the select
element:
您需要option
在循环中创建元素,设置属性和文本并将其附加到select
元素:
var select = document.createElement('select'),
option,
i = 0,
il = langArray.length;
for (; i < il; i += 1) {
option = document.createElement('option');
option.setAttribute('value', langArray[i].value);
option.appendChild(document.createTextNode(langArray[i].text));
select.appendChild(option);
}
This assumes that your langArray
looks something like this:
这假设您langArray
看起来像这样:
var langArray = [
{value: "val1", text: "text 1"},
{value: "val2", text: "text 2"}
];
You'll need to tweak the code to match your array
您需要调整代码以匹配您的数组
回答by MD. Mohiuddin Ahmed
var dynamicSelect = document.getElementById("selectID");
langArray.forEach(function(item){
{
var newOption = document.createElement("option");
newOption.text = item.toString();//item.whateverProperty
dynamicSelect.add(newOption);
//new select items should populated immediately
});
回答by Oliver
As a more 'up-to-date' method based on @Ibu's (currently accepted and perfectly valid) answer, you can use the forEach
method in JavaScript, like so:
作为基于@Ibu(当前接受且完全有效)答案的更“最新”方法,您可以forEach
在 JavaScript 中使用该方法,如下所示:
let select_elem = document.createElement('select');
langArray.forEach((element, index) => {
let option_elem = document.createElement('option');
// Add index to option_elem
option_elem.value = index;
// Add element HTML
option_elem.textContent = element;
// Append option_elem to select_elem
select_elem.appendChild(option_elem);
});
Using a forEach
method tracks its own index, meaning you don't need to have to manually track your index (using something like var i=0; [...] i++
) and is - I would argue - neater and more maintainable than a for
loop. After all, you don't need to create any variables outside of the loop, or manually increment those variables, and - consequently - there is less chance of conflicts if the index variable (say, var i
) is used elsewhere (e.g. if you have a loop within a loop).
使用forEach
方法跟踪它自己的索引,这意味着您不需要手动跟踪您的索引(使用类似var i=0; [...] i++
)并且 - 我认为 - 比for
循环更整洁,更易于维护。毕竟,您不需要在循环外创建任何变量,也不需要手动增加这些变量,因此,如果索引变量(例如,var i
)在其他地方使用(例如,如果您有一个循环内循环)。
It should be noted that this recommendation comes in a context - there will ultimately be contexts when a for
loop is a best choice, and when a forEach
loop will be a best choice. As I personally prioritise maintainability over speed, I would by default opt for a forEach
loop. But that's not to say that it is the correct or only correct answer. Always, always, ALWAYS consider your personal use requirements over the advice of anyone on the Internet.
应该注意的是,此建议是在上下文中提出的 - 最终将存在for
循环何时是最佳选择以及何时循环是最佳选择的上下文forEach
。由于我个人优先考虑可维护性而不是速度,因此我会默认选择forEach
循环。但这并不是说它是正确或唯一正确的答案。始终,始终,始终考虑您的个人使用要求,而不是 Internet 上任何人的建议。
I have also swapped innerHTML
for textContent
. Ultimately the content within the option is always going to be text (you can't add HTML to an option) so using textContent
is more descriptive to what you are ultimately going to be doing. And textContent
is more performant than innerHTML
as it does not parse the data being fed in. In fact, a benchmark shows that just changing innerHTML
to textContent
can improve performance by over x2.5.
我也换innerHTML
了textContent
。最终,选项中的内容始终是文本(您不能将 HTML 添加到选项中),因此使用textContent
更能描述您最终要做的事情。并且textContent
比innerHTML
不解析输入的数据性能更高。事实上,基准测试表明,只需更改innerHTML
为textContent
就可以将性能提高 x2.5 以上。
As such this is likely to be more performant andmore maintainable for those reading your code in the future. In this instance, unlike with a for
loop, I can see no benefit to notusing textContent
over innerHTML
.
因此这很可能是更好的性能和更高的可维护性对于那些阅读你的代码的未来。在这种情况下,与for
循环不同,我认为不使用textContent
over没有任何好处innerHTML
。
Performance
表现
One thing to note is that for-in
loops are more performant than forEach
loops. Though this is somewhat trivial (especially given the context), and in my opinion you should always prioritise maintainability over mere speed... unless performance is a vital criteria for what you are making (like, for example, if you are iterating over 1000s of values regularly and are experiencing bottlenecks). As the old saying goes though, "premature optimisation is the root of all evil".
需要注意的一件事是for-in
循环比forEach
循环更高效。尽管这有点微不足道(尤其是考虑到上下文),但在我看来,您应该始终将可维护性置于单纯的速度之上……除非性能是您所做工作的重要标准(例如,如果您要迭代 1000 多次值定期并遇到瓶颈)。不过,正如一句老话所说,“过早的优化是万恶之源”。
Ultimately, maintainers of JS will work to increase the performance of most-used constructs, and the performance hit will in most cases be negligible and will probably decrease over time as devices get more powerful, and parsers are ever-more optimised.
最终,JS 的维护者将努力提高最常用结构的性能,在大多数情况下,性能损失可以忽略不计,并且可能会随着设备变得更强大和解析器不断优化而随着时间的推移而减少。
The performance of an application that cannot be readily maintained, however, can be very high indeed. And will only ever go up, as poor maintainability precedes more bugs being introduced over time. Shaving 0.002ms off a loop now is not going to have any noticeable impact going forwards. A future developer trying to add a <strong>
tag to an <option>
element because they read, innerHTML = ...
and assumed they could add HTML willhave an impact going forwards.
然而,一个不容易维护的应用程序的性能确实可以非常高。并且只会上升,因为随着时间的推移,可维护性差会导致更多的错误被引入。现在将循环减少 0.002 毫秒不会对未来产生任何明显影响。未来的开发人员试图为元素添加<strong>
标签,<option>
因为他们阅读innerHTML = ...
并假设他们可以添加 HTML将对未来产生影响。
Side note for older browsers
旧浏览器的旁注
The forEach
method works in all evergreen browsers, but not in IE11 or below. For this, you will need to either polyfill or use a service like Babelto compile the code into a pre-ES6 format.
该forEach
方法适用于所有常绿浏览器,但不适用于 IE11 或更低版本。为此,您需要使用 polyfill 或使用Babel 之类的服务将代码编译为 ES6 之前的格式。
You may also need to change the let
keyword to var
for older browsers too. The let
keyword doeswork in IE11, though it has a number of issues. If you do not require support for older browsers though, using the keywords let
and const
are great habits to get into.
对于旧版浏览器,您可能还需要将let
关键字更改var
为。该let
关键字在 IE11 中确实有效,但它有许多问题。如果您不需要对旧浏览器的支持,使用关键字let
和const
是很好的习惯。
回答by HappyCoder
Another way to do this:
另一种方法来做到这一点:
for (let i = 0; i < langArray.length; i++) {
let opt = document.createElement("option");
opt.value = langArray[i].id; //or i, depending on what you need to do
opt.innerHTML = langArray[i].name;
$('#some-input').append(opt); //Chuck it into the dom here if you want
}
- For loop is often simpler to understand.
- Adding the option during the loop will avoid overwriting css styles that may be set at the "select" level of the HTML.
- Will be marginally slower.
- For 循环通常更容易理解。
- 在循环期间添加该选项将避免覆盖可能在 HTML 的“选择”级别设置的 css 样式。
- 会稍微慢一点。
回答by Rick Turner
A dirty option would be to use divs and populate the select string (innerHTML) based on the previous selection. You can still use the langArray as mentioned above.
一个肮脏的选择是使用 div 并根据先前的选择填充选择字符串 (innerHTML)。您仍然可以使用上面提到的 langArray。