Adding options to select with javascript

后端 未结 9 1112
执念已碎
执念已碎 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:46

    I don't recommend doing DOM manipulations inside a loop -- that can get expensive in large datasets. 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:

    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.

提交回复
热议问题