Jos*_*ody 21 javascript ajax internet-explorer html-table cross-browser
我有一个AJAX应用程序,它下载一个JSON对象并使用这些数据使用Javascript DOM函数向HTML <table>添加行.它完美无缺......除了在Internet Explorer中.IE没有出现任何类型的错误,我已经尽可能地验证了浏览器正在执行的代码,但它根本没有效果.我创建了这个快速而脏的页面来演示问题:
<!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><title></title></head><body>
<table id="employeetable">
<tr>
<th>Name</th>
<th>Job</th>
</tr>
</table>
<script type="text/javascript">
function addEmployee(employeeName, employeeJob) {
var tableElement = document.getElementById("employeetable");
if (tableElement) {
var newRow = document.createElement("tr");
var nameCell = document.createElement("td");
var jobCell = document.createElement("td");
nameCell.appendChild(document.createTextNode(employeeName));
jobCell.appendChild(document.createTextNode(employeeJob));
newRow.appendChild(nameCell);
newRow.appendChild(jobCell);
tableElement.appendChild(newRow);
alert("code executed!");
}
}
setTimeout("addEmployee(\"Bob Smith\", \"CEO\");", 1000);
setTimeout("addEmployee(\"John Franks\", \"Vice President\");", 2000);
setTimeout("addEmployee(\"Jane Doe\", \"Director of Marketing\");", 3000);
</script>
</body></html>
Run Code Online (Sandbox Code Playgroud)
我没有尝试IE 8,但IE 7和IE 6都没有显示应该添加的额外行.我无法理解为什么.有谁知道这个问题的好方法,或者我可能做错了什么?
Wal*_*ess 17
您需要创建一个TBODY元素来添加新的TR,然后将TBODY添加到您的表中,如下所示:
<!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><title></title></head><body>
<table id="employeetable">
<tr>
<th>Name</th>
<th>Job</th>
</tr>
</table>
<script type="text/javascript">
function addEmployee(employeeName, employeeJob) {
var tableElement = document.getElementById("employeetable");
if (tableElement) {
var newTable = document.createElement('tbody'); // New
var newRow = document.createElement("tr");
var nameCell = document.createElement("td");
var jobCell = document.createElement("td");
nameCell.appendChild(document.createTextNode(employeeName));
jobCell.appendChild(document.createTextNode(employeeJob));
newRow.appendChild(nameCell);
newRow.appendChild(jobCell);
newTable.appendChild(newRow); // New
tableElement.appendChild(newTable); // New
alert("code executed!");
}
}
setTimeout("addEmployee(\"Bob Smith\", \"CEO\");", 1000);
setTimeout("addEmployee(\"John Franks\", \"Vice President\");", 2000);
setTimeout("addEmployee(\"Jane Doe\", \"Director of Marketing\");", 3000);
</script>
</body></html>
Run Code Online (Sandbox Code Playgroud)
显然,在IE中你需要将你的行追加到TBody元素,而不是Table元素......请参阅Ruby-Forum的讨论.
扩展讨论,<table>标记通常在没有显式<thead>和<tbody>标记的情况下完成,但是<tbody> ELEMENT是实际需要添加新行的地方,因为<table>不包含< tr>元素直接.