2014-01-23 46 views
0

我有一個div id .i必須在表格中附加一個值給div。jquery添加一個表格到div

<div id="testResult" style="padding-left: 120px; "></div> 

在做下面的步驟,但它不工作。

$.ajax({ 
    url: '/getReports', 
    cache: false 
}).done(function (html) { 
    if (html != "") { 
     $('#testResult').show(); 
     var htm = ""; 

     var string1 = '<table border="1"><tr><td>No</td><td>Testcase</td> <td>OS</td> <td>Browser</td> <td>Result</td></tr></table>'; 
     $.each(html, function (i, data) { 

      string1 + = '<tr><td rowspan="3">1</td><td rowspan="3">' + data.status.test + '</td><td rowspan="3"><!--OS--></td><td>' + data.status.bwser + '</td> <td> ' + data.status.report + ' </td></tr>'; 
     }); 
     $('#testResult ').append(string1); 
     $("#testResult").html("<br/><br/>"); 
     $("#testResult").html("<p>" + htm + "</p>"); 
    } 

}).fail(function() { 
    $("#testResult").html("Failed to run the test"); 
    $('#edit ').removeAttr("disabled"); 
}); 
+0

對不起...但它不起作用 – Sush

+3

您正在追加string1,那麼您將覆蓋「

」並再次覆蓋空htm。這是有道理的 –

+0

你用.html()覆蓋內容 – timo

回答

5

$("#testResult").html("<br/><br/>")$("#testResult").html("<p>" + htm + "</p>")將覆蓋 「的TestResult」 DIV的內容。因此,更換此

$('#testResult ').append(string1); 
     $("#testResult").html("<br/><br/>"); 
     $("#testResult").html("<p>" + htm + "</p>"); 
} 

$('#testResult ').append(string1); 
     $("#testResult").append("<br/><br/>"); 
     $("#testResult").append("<p>" + htm + "</p>"); 
} 

.append():會在哪裏爲

的.html到DIV 的現有內容中添加或添加額外的字符串( ):將刪除或覆蓋DIV的現有內容與較新的內容。

這是.append().html()之間的主要區別。

+0

@Pushkar:看到我更新的答案,應該可以幫助你理解兩者之間的主要區別。 –

2

編輯這部分

$("#testResult").append("<br/><br/>"); 
    Remove this part--> 
    $("#testResult").html("<p>" + htm + "</p>"); 

的htm是空字符串,因爲你從不將任何字符串它

+0

加入break有一定意義,但追加空字符串變量不會。謝謝我會'相應地編輯 –