How to create and append multiple dom elements efficiently

Deadly 提交于 2020-01-07 02:52:07

问题


I'm building 10 buttons on the DOM and want to see if there is a more efficient way of building them because it seems strange to be calling createElement and appendChild 10 times.

<script>
function makeAlertButtons () {
  var container = document.createElement("div")
  container.setAttribute('id', "container")
  document.getElementsByTagName('body')[0].appendChild(container)
  for (var x = 1; x <=10; x++) {
    var butt = document.createElement("button")
    butt.appendChild(document.createTextNode(x))
    document.getElementById("container").appendChild(butt)
  }
  document.getElementById("container").addEventListener('click', function (e) {
    alert(e.target.textContent)
  })
}
makeButtons()
</script>

回答1:


You can optimize your code by reusing the container variable and moving

document.getElementsByTagName('body')[0].appendChild(container);

after the loop

function makeAlertButtons () {
  var container = document.createElement("div")
  container.setAttribute('id', "container")
 
  for (var x = 1; x <=10; x++) {
    var butt = document.createElement("button")
    butt.appendChild(document.createTextNode(x))
    container.appendChild(butt)
  }

  document.getElementsByTagName('body')[0].appendChild(container);
  container.addEventListener('click', function (e) {
    alert(e.target.textContent)
  })
}

makeAlertButtons();



回答2:


"more efficient"? It would be more efficient at execution time if the DOM was just built with HTML. If you want the JavaScript to be more efficient, then you'll want to cache your JavaScript in the Client's Browser, by using an external <script type='text/javascript' src='yourJavaScriptPage.js'></script> tag like that in your <head>. I'm including some code here that may teach you something:

var pre = onload, doc, bod, htm, C, T, E, makeAlertButtons; // if using technique on multiple pages change pre var
onload = function(){ // window.onload Event
if(pre)pre(); // if previous onload execute it

doc = document; bod = doc.body; htm = doc.documentElement;
C = function(e){
  return doc.createElement(e);
}
T = function(n){
  return doc.getElementsByTagName(n);
}
E = function(id){
  return doc.getElementById(id);
}
makeConsoleButtons = function(count){
  var container = C('div');
  container.id = 'container';
  for(var i=1,l=count+1; i<l; i++){
    var butt = C('input');
    butt.type = 'button'; butt.value = i;
    butt.onclick = function(){ // note lazy style will overwrite - but it's faster to type
      console.log(this.value); // alert can create problems in old IE
    }
    container.appendChild(butt);
  }
  bod.appendChild(container);
}
makeConsoleButtons(10);

} // end window.onload

Hope you learned something.



来源:https://stackoverflow.com/questions/40186673/how-to-create-and-append-multiple-dom-elements-efficiently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!