问题是您正在使用document.write
按钮的单击事件,这是在文档关闭之后......这意味着它会覆盖所有内容。由于您的页面很简单并且只有一个<h1>
和按钮,因此看起来只有那些东西被隐藏了,但它会是页面上的所有内容(如果您有更多)。
解决方案是动态使用.appendChild
和/或.innerHTML
添加内容。我会在一分钟内提供解决方案:)
更新:
由于您使用的是表格,因此您不妨使用本机方法.insertRow
,.insertCell
这会使表格的创建更加容易。这是您可以整体使用的示例:
function CdCatalog(xmlDoc) {
var table = document.createElement("table");
var thead = table.createTHead(); // Where "header" rows go
// `insertRow` creates a <tr> element and appends it to `thead` automatically, returning the element
var tr = thead.insertRow(-1);
var td = document.createElement("th"); // No special method for creating "th" elements
td.innerHTML = "TITLE"; // Set its inner content
tr.appendChild(th); // Add it to the row (which is in the header)
td = document.createElement("td");
td.innerHTML = "YEAR";
tr.appendChild(td);
var x = xmlDoc.getElementsByTagName("CD");
// "tbody" is where a table's content goes, whether you do this explicitly or not
var tbody = table.tBodies[0];
for (var i = 0; i < x.length; i++) {
tr = tbody.insertRow(-1);
// `insertCell` creates a <td> element and appends it to `tr` automatically, returning the element
td = tr.insertCell(-1);
td.innerHTML = x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
td = tr.insertCell(-1);
td.innerHTML = x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
// Actually add the table to the DOM (the <body> element in this case)...you can specify where else to put it
document.body.appendChild(table);
}
// Make sure DOM is ready for manipulation
window.onload = function () {
var btn = document.getElementById("button_id"); // Whatever your button is
// Bind the "click" event for the button
btn.onclick = function () {
// Make your AJAX request
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "cd_catalog.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
// Pass the result to the function, instead of making everything global and sharing
CdCatalog(xmlDoc);
};
};
除非我弄错了,否则你不能嵌套<td>
在<table>
......你必须将它们<tr>
嵌套在......嵌套在<table>