如何有效地创建和附加多个dom元素

时间:2016-10-21 23:19:23

标签: javascript html dom domdocument elements

我在DOM上构建了10个按钮,想要查看是否有更有效的方法来构建它们,因为调用createElementappendChild 10次似乎很奇怪。

<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>

2 个答案:

答案 0 :(得分:1)

您可以通过重用容器变量并移动

来优化代码
document.getElementsByTagName('body')[0].appendChild(container);

循环之后

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

答案 1 :(得分:0)

&#34;效率更高&#34;?如果DOM仅使用HTML构建,那么在执行时它会更有效。如果您希望JavaScript更高效,那么您希望通过使用<script type='text/javascript' src='yourJavaScriptPage.js'></script>中的外部<head>标记,将JavaScript缓存在客户端浏览器中。我在这里包含了一些可能会教你一些东西的代码:

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

希望你能学到一些东西。

相关问题