table中插入行、删除行操作、撤销操作:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>测试js创建dom生成的html如何换行</title> <style> .editor { width: 100%; height: 300px; background-color: #ecf8ff; border: 0; } </style> </head> <body> <iframe class="editor" src="template.html"></iframe> <div> <button onclick="showHTML()">showHTML</button> <br> <button onclick="innertTR()">插入一行</button> <br> 输入行数:<input type="text" name="row"/> <button onclick="removeRow()">删除行</button> <br> <button onclick="redo()">撤销</button> </div> </body> </html> <script> var iframe; var iframeBody; var table; var history = { target: null, addedNodes: [], removedNodes: [], nextSibling: null, previousSibling: null } window.onload = function () { iframe = document.querySelector('.editor'); iframeBody = iframe.contentDocument.body; table = iframeBody.getElementsByTagName('table')[0]; // 撤销操作的实现 var observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { history.target = mutation.target; history.addedNodes = mutation.addedNodes; history.removedNodes = mutation.removedNodes; history.nextSibling = mutation.nextSibling; history.previousSibling = mutation.previousSibling; }) }) observer.observe(iframe.contentDocument.body.querySelector('.layout'),{ childList: true, subtree: true }) } function innertTR() { table.appendChild(document.createTextNode('\n')); table.appendChild(createTR()); } function removeRow() { const row = document.querySelector('input[name=\'row\']').value; const trs = table.getElementsByTagName('TR'); table.removeChild(trs[row -1]); } function createTR() { const tr = document.createElement('tr'); tr.appendChild(document.createTextNode('\n')); tr.appendChild(createTD()); tr.appendChild(document.createTextNode('\n')); tr.appendChild(createTD()); tr.appendChild(document.createTextNode('\n')); tr.appendChild(createTD()); tr.appendChild(document.createTextNode('\n')); tr.appendChild(createTD()); tr.appendChild(document.createTextNode('\n')); return tr; } function createTD() { const td = document.createElement('td'); td.innerHTML = 'test' + parseInt(Math.random() * 100); return td; } function showHTML() { console.log(iframe.contentDocument.body.innerHTML) } function redo() { if (history.addedNodes.length > 0) {//撤销添加操作 history.addedNodes.forEach(function (node) { history.target.removeChild(node); }) } else { //撤销删除操作 history.removedNodes.forEach(function (node) { if (history.nextSibling === null) { history.target.appendChild(node) } else { history.target.insertBefore(node,history.nextSibling); } }) } } </script>template.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>template</title> <style> td { border: 1px solid #7970ff; } </style> </head> <body> <div class="layout"> <table> </table> </div> </body> </html>