0
我使用简洁的JavaScript和Jquery的混合来动态创建表格。我使用for循环遍历Ajax调用返回的数据,但它不会创建新行。所以我使用alert来输出html,我可以看到有很多表格元素,包括一个显示的tbody,尽管我没有明确地创建一个tbody。JavaScript createElement表格添加不需要的tbody
Ajax代码,其中的“完成”,我创建一个表:
function performSearch(){
var q = $("input[name='search']").val();
var url = "performsearch.php";
$.ajax({
url: url,
method: "post",
data: { 'q' : q },
dataType: "json"
}).done(function(data) {
/* the table creating part of the code - something wrong in here */
var output = $("#output");
var table = document.createElement("table");
var tr = document.createElement("tr");
var td = document.createElement("td");
var button = document.createElement("button");
output.append($(table));
$(table).append($(tr));
$(tr).append($(td).attr("colspan","100%"));
$(td).append($(button).attr("type","button").on("click",function() {
exportOutput(data);
}).html("Export"));
$(table).append("<tr>\n"); // I'm clearly adding a tr tag, but it doesn't show up
$(table).append(" <th>id</th>\n");
$(table).append(" <th>processed thru</th>\n");
$(table).append("</tr>"); //ending the tr tag
for(i=0;i<data.length;i++){ //let's say only one record is returned
$(table).append("<tr>\n"); //clearly adding a tr tag, but it's not showing up
$(table).append(" <td>"+data[i]['id']+"</td>\n");
$(table).append(" <td>"+data[i]['processed_thru']+"</td>\n");
$(table).append("</tr>\n");
}
}).
fail(function(jqXHR, textStatus) {
alert("Request failed: " + jqXHR + ", " + textStatus);
});
}
下面是它的生产HTML:
<table>
<tbody> <!-- look at tbody tag, where'd it come from? -->
<tr><td colspan="100%"><button type="button">Export</button></td></tr>
<tr></tr> <!-- look at this extra tr tag, where'd it come from? -->
<tr></tr>\n\ <!-- look at this extra tr tag, where'd it come from? -->
</tbody>\n\ <!-- I didn't add this -->
<th>id</th> <!-- th tag not wrapped in a tr tag -->
<th>processed thru</th>
<th>status</th>
<td>1568</td> <!-- td tags not wrapped in row tag -->
<td>06/03/2016</td>
<td>ACTIVE</td> <!-- no tr tag following the end of the td tags -->
</table>
代码的一部分正确创建元素,而部分则不创建元素。一半下来,你切换到使用HTML,但你做错了。 DOM不是一个字符串。 – 2016-06-14 23:23:34
@squint啊,我明白你在说什么了。我会修复,并报告回来。 – TARKUS
如果'
回答
我把意见,并将它们用于以削减代码下来使用所有DOM方法创建内容,只有一个字符串用于定义iframe样式。许多代码行因此被修剪:
来源
2016-06-15 00:38:16 TARKUS
如果这是混合编程风格鸡尾酒的练习,那么它很有趣。仅供参考:表DOM有许多特定的方法,比如'table.insertRow','table.createTHead','row.insertCell'列举少量。 –
@AlexKudryashev我会探讨一些建议。相信我,我宁愿没有混合这种鸡尾酒。最初我完全使用串联字符串构造表格,但是当尝试使用按钮(也是在字符串内)将返回的数据对象传递给另一个函数时,问题就出现了。最后,我必须使用DOM方法创建按钮,以及它的父级td,tr和表。但是我没有写出表格的其余部分,特别是FOR循环中的行,使用DOM方法,所以我使用一个字符串编写一个新表。这很简单直接。 – TARKUS
编程“鸡尾酒”(主要)在回答中被淘汰。谢谢! – TARKUS
相关问题