2011-07-18 24 views
0

這部分代碼是首先獲取數據並顯示XML文件中的數據。之後,有一個名爲submit的按鈕。當我按下提交,它會調用該函數add(),它將第一個節點從XML文件複製:JavaScript克隆XML節點問題

<html> 
<body> 
<link rel="stylesheet" type="text/css" href="test.css" /> 
<table> 
</tr class="top"> 
<td>ID</td> 
<td>Orgin</td> 
<td>Type</td> 
<td>Color</td> 
</tr> 

<script type="text/javascript"> 
xmlhttp=new XMLHttpRequest(); 
xmlhttp.open("GET","test.xml",false); 
xmlhttp.send(); 
xmlDoc=xmlhttp.responseXML; 
var x=xmlDoc.getElementsByTagName("product"); 
for (i=0;i<x.length;i++) 
    { 
    document.write("<tr class=a><td>"); 
    document.write(x[i].getElementsByTagName("orgin")[0].getAttribute("id")); 
    document.write("</td><td>"); 
    document.write(x[i].getElementsByTagName("orgin")[0].childNodes[0].nodeValue); 
    document.write("</td><td>"); 
    document.write(x[i].getElementsByTagName("type")[0].childNodes[0].nodeValue); 
    document.write("</td><td>"); 
    document.write(x[i].getElementsByTagName("color")[0].childNodes[0].nodeValue); 
    document.write("</td></tr>"); 
    } 
document.write("</table>"); 

function add() 
{var id=document.getElementById('idProduct').value; 
var time=document.getElementById('Time').value; 
var org=document.getElementById('orgin').value; 
var color=document.getElementById('color').value; 
var type=document.getElementById('type').value; 

xmlDoc=loadXMLDoc("test.xml"); //Problem happen here, the code doesn't functioning 
oldNode=xmlDoc.getElementsByTagName('product')[1]; 
newNode=oldNode.cloneNode(true); 
xml.Doc.documentElement.appendChild(newNode); 
} 

</script> 
<br> 
Inputs: 
<br> 
Time: <input type="text" id="time"><br> 
ID: <input type="text" id="idProduct"><br> 
Orgin: <input type="text" name="orgin"><br> 
Type: <input type="text" name="type"><br> 
Color: <input type="text" name="color"><br> 
<input type="button" value="submit" onclick="add()"></input> 


</body> 
</html> 

這是XML文件:

<?xml version="1.0" encoding="Big5" ?> 
<set> 
    <product time="5"> 
    <orgin id="1">sony</orgin> 
    <type>comp</type> 
    <color>red</color> 
    </product> 
    <product time="6"> 
    <orgin id="2">apple</orgin> 
    <type>others</type> 
    <color>blue</color> 
    </product> 
</set> 
+0

函數* loadXMLDoc *定義在哪裏?在我看來,在你調用函數的地方,* xmlDoc *已經是一個XML文檔。更進一步,你有'xml.Doc.documentElement'這可能應該是'xmlDoc.documentElement'。 – RobG

+0

另外,你真的應該把整個表格作爲一個HTML字符串寫出來,document.write它分成部分是一個非常糟糕的主意 - 當每個寫入完成時,HTML分析器是如何構成的?無論如何,HTML看起來無效。 – RobG

+0

謝謝。我修改了xml.Doc.documentElement。我想知道定義loadXMLDoc是什麼意思? 我在這裏以下指令: http://www.w3schools.com/dom/dom_nodes_clone.asp –

回答

0

這裏是W3Schools的loadxmldoc.js文件:

function loadXMLDoc(dname) 
{ 
if (window.XMLHttpRequest) 
    { 
    xhttp=new XMLHttpRequest(); 
    } 
else 
    { 
    xhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xhttp.open("GET",dname,false); 
xhttp.send(); 
return xhttp.responseXML; 
} 

將其添加到您的腳本塊,它可能會開始工作(或讓你更進一步)。