溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JS實現(xiàn)動態(tài)添加DOM節(jié)點和事件的方法示例

發(fā)布時間:2020-09-15 13:45:09 來源:腳本之家 閱讀:373 作者:zxl0016 欄目:web開發(fā)

本文實例講述了JS實現(xiàn)動態(tài)添加DOM節(jié)點和事件的方法。分享給大家供大家參考,具體如下:

運行效果圖如下:

JS實現(xiàn)動態(tài)添加DOM節(jié)點和事件的方法示例

完整實例代碼如下:

<!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)動態(tài)添加節(jié)點和事件</title>
<script type="text/javascript">
function addEl(){
  //找到要添加節(jié)點的父節(jié)點(table)
  var tb = document.getElementById("tb");
  //創(chuàng)建tbody節(jié)點,表格中必須有tbody才能添加,直接添加tr不成功
  var tbody = document.createElement("tbody");
  //創(chuàng)建tr節(jié)點
  var tr = document.createElement("tr");
  //創(chuàng)建td節(jié)點
  var td = document.createElement("td");
  //添加一個文本框節(jié)點,設置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事件,和事件執(zhí)行的函數(shù)
  newEl.onclick = function dofun(){
  document.getElementById("txt").value += newTp.value;
  }
  //把2個節(jié)點添加到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>
   添加節(jié)點的地方
  </td>
  </tr>
</table>
<table>
  <tr>
  <td>
   <input type="button" value="添加節(jié)點" onclick="addEl()" />
  </td>
  <td>
   <input type="text" id="txt"/>
  </td>
  </tr>
</table>
</body>
</html>

更多關于JavaScript相關內(nèi)容感興趣的讀者可查看本站專題:《JavaScript操作DOM技巧總結(jié)》、《JavaScript錯誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學運算用法總結(jié)》

希望本文所述對大家JavaScript程序設計有所幫助。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI