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
相關問題