欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JS实现动态添加DOM节点和事件的方法示例

程序员文章站 2023-08-13 18:04:03
本文实例讲述了js实现动态添加dom节点和事件的方法。分享给大家供大家参考,具体如下: 运行效果图如下: 完整实例代码如下:

本文实例讲述了js实现动态添加dom节点和事件的方法。分享给大家供大家参考,具体如下:

运行效果图如下:

JS实现动态添加DOM节点和事件的方法示例

完整实例代码如下:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en"
"http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>js(dom)动态添加节点和事件</title>
<script type="text/javascript">
function addel(){
  //找到要添加节点的父节点(table)
  var tb = document.getelementbyid("tb");
  //创建tbody节点,表格中必须有tbody才能添加,直接添加tr不成功
  var tbody = document.createelement("tbody");
  //创建tr节点
  var tr = document.createelement("tr");
  //创建td节点
  var td = document.createelement("td");
  //添加一个文本框节点,设置id和type属性
  var newtp = document.createelement("input");
  newtp.id = "text1";
  newtp.type = "text";
  //添加一个按钮
  var newel = document.createelement("input");
  newel.type = 'button';
  newel.value = "button";
  newel.name = "button1";
  //添加onclick事件,和事件执行的函数
  newel.onclick = function dofun(){
  document.getelementbyid("txt").value += newtp.value;
  }
  //把2个节点添加到td当中
  td.appendchild(newtp)
  td.appendchild(newel);
  //把td添加到tr中
  tr.appendchild(td);
  //把tr添加到td中
  tbody.appendchild(tr);
  //把td添加到table中
  tb.appendchild(tbody);
}
</script>
</script>
</head>
<body>
<table id="tb">
  <tr>
  <td>
   添加节点的地方
  </td>
  </tr>
</table>
<table>
  <tr>
  <td>
   <input type="button" value="添加节点" onclick="addel()" />
  </td>
  <td>
   <input type="text" id="txt"/>
  </td>
  </tr>
</table>
</body>
</html>

更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript操作dom技巧总结》、《javascript错误与调试技巧总结》、《javascript数据结构与算法技巧总结》、《javascript遍历算法与技巧总结》及《javascript数学运算用法总结

希望本文所述对大家javascript程序设计有所帮助。