简体   繁体   English

使用 javascript 向 select 添加选项

[英]Adding options to select with javascript

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.我希望这个 javascript 在 id="mainSelect" 的 select 中创建从 12 到 100 的选项,因为我不想手动创建所有选项标签。 Can you give me some pointers?你能给我一些指示吗? Thanks谢谢

function selectOptionCreate() {

  var age = 88;
  line = "";
  for (var i = 0; i < 90; i++) {
    line += "<option>";
    line += age + i;
    line += "</option>";
  }

  return line;
}

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 Fiddle demo . JS 小提琴演示

JS Perf comparison 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.我的和Sime Vidas 的答案JS Perf比较,运行是因为我认为他看起来比我的更易于理解/直观,我想知道这将如何转化为实施。 According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.根据 Chromium 14/Ubuntu 11.04,我的速度要快一些,但其他浏览器/平台可能会产生不同的结果。


Edited in 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);

JS Fiddle demo . JS 小提琴演示

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
});

JS Fiddle demo . JS 小提琴演示

References:参考:

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]); HTMLSelect​Element​.add (item[, before]);
new Option (text, value, defaultSelected, selected); 新选项(文本、值、默认选择、选择);

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/

I don't recommend doing DOM manipulations inside a loop -- that can get expensive in large datasets.我不建议在循环中进行 DOM 操作——这在大型数据集中会变得很昂贵。 Instead, I would do something like this:相反,我会做这样的事情:

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.它用作 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.关键区别在于,由于文档片段不是实际 DOM 结构的一部分,因此对片段所做的更改不会影响文档、导致重排或在进行更改时产生任何性能影响。

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 分配给另一个 select 元素 - 从而通过重复函数调用避免不必要的循环。

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;

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.最后我用select2的数据属性解决了我的问题。 I used json and got the array and then give it in select2 element initialize.我使用 json 并获取了数组,然后在 select2 元素初始化中将其提供。 For more detail you can see my answer at below post.有关更多详细信息,您可以在下面的帖子中查看我的答案。

https://stackoverflow.com/a/41297283/4928277 https://stackoverflow.com/a/41297283/4928277

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);您可以使用selectEl.insertAdjacentHTML('afterbegin', str); to add them to the top instead.而是将它们添加到顶部。
And selectEl.insertAdjacentHTML('beforeend', str);selectEl.insertAdjacentHTML('beforeend', str); to add them to the bottom of the list.将它们添加到列表的底部。

IE11 compatible syntax: IE11 兼容语法:

array.map(function (c) { return '<option value="'+c.id+'">'+c.name+'</option>'; }).join('');

 for (let i = 12; i< 101; i++){ let html = "" html += ` <option value="${i}">${i}</option> ` mainSelect.innerHTML += html }
 const mainSelect = document.getElementById("mainSelect")
This is a very easy-to-understand way to solve your problem! 这是解决您问题的一种非常容易理解的方法! Hope it heps:) 希望它帮助:)

var selectElement = document.getElementById('ageselect');

for (var age = 12; age <= 100; age++) {
  selectElement.add(new Option(age, age));
}


Your age: <select id="ageselect"><option value="">Please select</option></select>

Notice the value was added as a second parameter to new Option请注意,该值已作为第二个参数添加到 new Option

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM