我試圖打印出用戶在textarea中編寫的HTML代碼的DOM樹,但我無法打印出在textarea中鍵入的代碼。在新窗口中打印HTML代碼的DOM樹
<html>
<head>
<title> HTML Tree Structure </title>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
function traverseDOMTree(targetDocument, currentElement, depth) {
if (currentElement) {
var j;
var tagName = currentElement.tagName;
// Prints the node tagName, such as <A>, <IMG>, etc
if (tagName)
targetDocument.writeln("<"+currentElement.tagName+">");
else
targetDocument.writeln("[unknown tag]");
// Traverse the tree
var i = 0;
var currentElementChild = currentElement.childNodes[i];
while (currentElementChild) {
// Formatting code (indent the tree so it looks nice on the screen)
targetDocument.write("<BR>\n");
for (j = 0; j < depth; j++) {
// ¦ is just a vertical line
targetDocument.write(" ¦");
}
targetDocument.writeln("<BR>");
for (j = 0; j < depth; j++) {
targetDocument.write(" ¦");
}
if (tagName)
targetDocument.write("--");
// Recursively traverse the tree structure of the child node
traverseDOMTree(targetDocument, currentElementChild, depth+1);
i++;
currentElementChild=currentElement.childNodes[i];
}
// The remaining code is mostly for formatting the tree
targetDocument.writeln("<BR>");
for (j = 0; j < depth - 1; j++) {
targetDocument.write(" ¦");
}
targetDocument.writeln(" ");
if (tagName)
targetDocument.writeln("</"+tagName+">");
}
}
function printDOMTree(domElement, destinationWindow) {
var outputWindow = destinationWindow;
if (!outputWindow)
outputWindow = window.open();
outputWindow.document.open("text/html", "replace");
outputWindow.document.write("<HTML><HEAD><TITLE>DOM</TITLE></HEAD><BODY>\n");
outputWindow.document.write("<CODE>\n");
traverseDOMTree(outputWindow.document, domElement, 1);
outputWindow.document.write("</CODE>\n");
outputWindow.document.write("</BODY></HTML>\n");
outputWindow.document.close();
}
</SCRIPT>
<DIV ID="myDiv">
<form>
<textarea name="htmlcode" id="htmlCode"
style="width: 400px; height: 100px">
</textarea>
<br/>
<input type="button" value="Show me the DOM Tree"
onClick="javascript=printDOMTree(document.getElementById('htmlCode')); return true;" />
<br/>
</form>
</DIV>
</body>
</html>
我不能讓輸入按鈕和printDOMTree
函數讀什麼用戶進入textarea
類型的工作。我的代碼的HTML部分有什麼問題?我該如何改進並使其工作?
我測試過你編輯過的代碼,看起來有些問題已經修復了,但是仍然沒有打印任何寫在textarea中的html代碼的DOM樹,它只是說未知的標籤。 它沒有讀取用戶輸入的textarea的值。 –
看看[這個](http://jsfiddle.net/wimplash/5Ev6F/)。您可能仍然需要處理文本節點等事情,您可能需要再次調整格式。 –
你做了我的一天,我將在格式上工作。 –