添加选项以使用 javascript 进行选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8674618/
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
Adding options to select with javascript
提问by Hymantheripper
I want this javascript to create options from 12 to 100 in a select with id="mainSelect", because I do not want to create all of the option tags manually. Can you give me some pointers? Thanks
我希望这个 javascript 在 id="mainSelect" 的选择中创建从 12 到 100 的选项,因为我不想手动创建所有选项标签。你能给我一些指点吗?谢谢
function selectOptionCreate() {
var age = 88;
line = "";
for (var i = 0; i < 90; i++) {
line += "<option>";
line += age + i;
line += "</option>";
}
return line;
}
回答by David says reinstate Monica
You could achieve this with a simple for
loop:
您可以通过一个简单的for
循环来实现这一点:
var min = 12,
max = 100,
select = document.getElementById('selectElementId');
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
JS Perfcomparison of both mine and Sime Vidas' answer, run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.
我和Sime Vidas 的答案的JS Perf比较,运行是因为我认为他的看起来比我的更容易理解/直观,我想知道这将如何转化为实现。根据 Chromium 14/Ubuntu 11.04,我的速度稍快,但其他浏览器/平台可能会有不同的结果。
Editedin response to comment from OP:
针对 OP 的评论进行了编辑:
[How] do [I] apply this to more than one element?
[如何] [我] 将其应用于多个元素?
function populateSelect(target, min, max){
if (!target){
return false;
}
else {
var min = min || 0,
max = max || min + 100;
select = document.getElementById(target);
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
}
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);
// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');
// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);
And, finally (after quite a delay...), an approach extending the prototype of the HTMLSelectElement
in order to chain the populate()
function, as a method, to the DOM node:
并且,最后(后相当的延迟...),延伸的原型的方法HTMLSelectElement
,以链的populate()
功能,作为一种方法,对DOM节点:
HTMLSelectElement.prototype.populate = function (opts) {
var settings = {};
settings.min = 0;
settings.max = settings.min + 100;
for (var userOpt in opts) {
if (opts.hasOwnProperty(userOpt)) {
settings[userOpt] = opts[userOpt];
}
}
for (var i = settings.min; i <= settings.max; i++) {
this.appendChild(new Option(i, i));
}
};
document.getElementById('selectElementId').populate({
'min': 12,
'max': 40
});
References:
参考:
回答by ?ime Vidas
Here you go:
干得好:
for ( i = 12; i <= 100; i += 1 ) {
option = document.createElement( 'option' );
option.value = option.text = i;
select.add( option );
}
Live demo:http://jsfiddle.net/mwPb5/
现场演示:http : //jsfiddle.net/mwPb5/
Update:Since you want to reuse this code, here's the function for it:
更新:由于您想重用此代码,这是它的功能:
function initDropdownList( id, min, max ) {
var select, i, option;
select = document.getElementById( id );
for ( i = min; i <= max; i += 1 ) {
option = document.createElement( 'option' );
option.value = option.text = i;
select.add( option );
}
}
Usage:
用法:
initDropdownList( 'mainSelect', 12, 100 );
Live demo:http://jsfiddle.net/mwPb5/1/
现场演示:http : //jsfiddle.net/mwPb5/1/
回答by thdoan
I don't recommend doing DOM manipulations inside a loop -- that can get expensive in large datasets. Instead, I would do something like this:
我不建议在循环内进行 DOM 操作——这在大型数据集中可能会变得昂贵。相反,我会做这样的事情:
var elMainSelect = document.getElementById('mainSelect');
function selectOptionsCreate() {
var frag = document.createDocumentFragment(),
elOption;
for (var i=12; i<101; ++i) {
elOption = frag.appendChild(document.createElement('option'));
elOption.text = i;
}
elMainSelect.appendChild(frag);
}
You can read more about DocumentFragment on MDN, but here's the gist of it:
你可以在MDN上阅读更多关于 DocumentFragment 的信息,但这里是它的要点:
It is used as a light-weight version of Document to store a segment of a document structure comprised of nodes just like a standard document. The key difference is that because the document fragment isn't part of the actual DOM's structure, changes made to the fragment don't affect the document, cause reflow, or incur any performance impact that can occur when changes are made.
它用作 Document 的轻量级版本,用于存储由节点组成的文档结构的片段,就像标准文档一样。关键区别在于,由于文档片段不是实际 DOM 结构的一部分,因此对片段所做的更改不会影响文档、不会导致重排或在进行更改时可能发生的任何性能影响。
回答by user
The most concise and intuitive way would be:
最简洁直观的方式是:
var selectElement = document.getElementById('ageselect');
for (var age = 12; age <= 100; age++) {
selectElement.add(new Option(age));
}
Your age: <select id="ageselect"><option value="">Please select</option></select>
You can also differentiate the name and the value or add items at the start of the list with additional parameters to the used functions:
HTMLSelect?Element?.add(item[, before]);
new Option(text, value, defaultSelected, selected);
您还可以区分名称和值或在列表的开头添加项目,并为使用的函数添加附加参数:
HTMLSelect?Element?.add(item[, before]);
新选项(文本、值、defaultSelected、selected);
回答by smnbss
See: What is the best way to add options to a select from an array with jQuery?
请参阅:使用 jQuery 从数组中选择添加选项的最佳方法是什么?
$('#mySelect')
.append($('<option>', { value : key })
.text(value));
回答by kinakuta
The one thing I'd avoid is doing DOM operations in a loop to avoid repeated re-renderings of the page.
我要避免的一件事是在循环中执行 DOM 操作以避免重复重新呈现页面。
var firstSelect = document.getElementById('first select elements id'),
secondSelect = document.getElementById('second select elements id'),
optionsHTML = [],
i = 12;
for (; i < 100; i += 1) {
optionsHTML.push("<option value=\"Age" + i + "\">Age" + i + "</option>";
}
firstSelect.innerHTML = optionsHTML.join('\n');
secondSelect.innerHTML = optionsHTML.join('\n');
Edit: removed the function to show how you can just assign the html you've built up to another select element - thus avoiding the unnecessary looping by repeating the function call.
编辑:删除了该函数以显示如何将您构建的 html 分配给另一个选择元素 - 从而通过重复函数调用避免不必要的循环。
回答by mohan mu
When you create a new Option
object, there are two parameters to pass: The first is the text you want to
appear in the list, and the second the value to be assigned to the option.
创建新Option
对象时,有两个参数要传递:第一个是要出现在列表中的文本,第二个是要分配给选项的值。
var myNewOption = new Option("TheText", "TheValue");
You then simply assign this Option
object to an empty array element, for example:
然后,您只需将此Option
对象分配给一个空数组元素,例如:
document.theForm.theSelectObject.options[0] = myNewOption;
回答by user
Often you have an array of related records, I find it easy and fairly declarative to fill select
this way:
通常您有一系列相关记录,我发现以select
这种方式填充很容易且相当声明:
selectEl.innerHTML = array.map(c => '<option value="'+c.id+'">'+c.name+'</option>').join('');
This will replace existing options.
You can use selectEl.insertAdjacentHTML('afterbegin', str);
to add them to the top instead.
And selectEl.insertAdjacentHTML('beforeend', str);
to add them to the bottom of the list.
这将替换现有选项。
您可以使用selectEl.insertAdjacentHTML('afterbegin', str);
将它们添加到顶部。
并且selectEl.insertAdjacentHTML('beforeend', str);
将它们添加到列表的底部。
IE11 compatible syntax:
IE11 兼容语法:
array.map(function (c) { return '<option value="'+c.id+'">'+c.name+'</option>'; }).join('');
回答by Engin Aydogdu
None of the above solutions worked for me. Append method didn't give error when i tried but it didn't solve my problem. In the end i solved my problem with data property of select2. I used json and got the array and then give it in select2 element initialize. For more detail you can see my answer at below post.
以上解决方案都不适合我。当我尝试时,追加方法没有给出错误,但它没有解决我的问题。最后我用select2的数据属性解决了我的问题。我使用了 json 并获取了数组,然后在 select2 元素初始化中给出它。有关更多详细信息,您可以在下面的帖子中看到我的回答。