本文實例講述了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é)點,設(shè)置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當(dāng)中 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>更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript操作DOM技巧總結(jié)》、《JavaScript錯誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運算用法總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計有所幫助。
新聞熱點
疑難解答