Adding options to select with javascript

后端 未结 9 1146
执念已碎
执念已碎 2020-11-22 15:40

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

9条回答
  •  梦谈多话
    2020-11-22 15:58

    The one thing I'd avoid is doing DOM operations in a loop to avoid repeated re-renderings of the page.

    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("";
    }
    
    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.

提交回复
热议问题