如何有效地创建和添加多个dom元素 [英] How to create and append multiple dom elements efficiently

查看:470
本文介绍了如何有效地创建和添加多个dom元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在DOM上构建10个按钮,并想查看是否有一种更有效的构建按钮的方法,因为调用 createElement 和<$似乎很奇怪c $ c> appendChild 10次。

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>


推荐答案

您可以通过重用容器变量和

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

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

这篇关于如何有效地创建和添加多个dom元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆