2016-04-23 57 views
-1

我想通過document.write()在javascript中打印一個字符串,但它看起來像當我使用document.write()函數中的其他代碼不再工作。如何在javascript中將字符串打印到html?

JavaScript代碼:

 <script type="text/javascript"> 
      var my_d = {{ pass_kegg|safe }}; 
      var myList_tmp = {{ pass_tmp|safe }}; 

      var epgd = "EPGD" 
      var kegg = "KEGG" 
      function buildHtmlTable(myList,printSource) { 
       var columns = addAllColumnHeaders(myList); 
       document.write(printSource); 
       // Builds the HTML Table out of myList json data from Ivy restful service. 
      } 


      function addAllColumnHeaders(myList) { 
      // Adds a header row to the table and returns the set of columns. 
      // Need to do union of keys from all records as some records may not contain 
      // all records 
      } 
    </script> 

HTML代碼:

<body onload="buildHtmlTable(my_d, epgd);buildHtmlTable(myList_tmp, kegg)"> 
     <table id="excelDataTable" border="1"> 
     </table> 
</body> 

本來有從JSON轉換HTML表格可在webpage.But可以看出,當我使用document.write()打印字符串epgd只有兩個字符串可以在我的網頁中看到。好像其他代碼一直沒有運行。我已經搜索了這個問題,有人說document.write()只能與頁面onload一起使用,但如果在運行時使用它,它會替換整個文檔。因此除了document.write()之外,任何人都可以爲我提供打印字符串在JavaScript中?

+0

你是否已經調查了明確操縱DOM,而不是文件。寫?像document.createElement,'document.findElementByID(「mytableid」)。appendChild(htmlstring)'etc? – morksinaanab

回答

0

首先嚐試:

document.getElementById("mytableid").innerHTML += "<tr><td>str</td></tr>"; 

但我認爲是這樣的:

var myTable = document.getElementById("myTableId"); 
var row = myTable.insertRow(-1); 
var cell = roww.insertCell(-1); 
cell.textContent="data1"; 

例如,如果你有

var data = [ 
    [ "one" , "two" ], 
    [ "alpha", "betha" ], 
    [ "a", "b" ] 
]; 
var myTable = document.getElementById("myTableId"); 
data.forEach(function(dataRows){ 
    var row = myTable.insertRow(-1); 
    dataRows.forEach(function(dataCell){ 
     var cell = row.insertCell(-1); 
     cell.textContent = dataCell; 
    }); 
}); 
+0

謝謝您的詳細解答! –

相關問題