2016-03-02 77 views
-3

我用insertAfter(根據How to do insert After() in JavaScript without using a library?),但是,在我的情況下,它不起作用。javascript insertAfter不起作用

爲什麼?

<!doctype html> 
<html lang="en"> 
    <head></head> 
    <body> 
     <table id="myTable"> 
      <tbody> 
       <tr> 
        <td></td> 
        <td></td> 
       </tr> 
       <tr> 
        <td></td> 
        <td></td> 
       </tr> 
      </tbody> 
     </table> 
     <script> 
      function insertAfter(newNode, referenceNode) { 
       referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); 
      } 

      _table = document.getElementById("myTable"); 
      _tbody = _table.getElementsByTagName("tbody")[0]; 
      n = _tbody.getElementsByTagName("TR").length; 
      _referenceNode = _tbody.getElementsByTagName("TR")[n - 1] 

      _newTR = "<tr><td>A very complex table<td></td><td>much more complex than in this example</td></tr>"; 

      parser = new DOMParser() 
      _newNode = parser.parseFromString(_newTR, "text/xml"); 

      insertAfter(_newNode, _referenceNode); 
     </script> 
    </body> 
</html> 
+3

[你真的只是問這個問題詢問(http://stackoverflow.com/questions/35758680/how-to-fix-this-javascript-error-當創造-A-復表動態地)。你想成爲被禁止的問題嗎?因爲刪除和重新分析問題就是你如何得到禁止的問題。 –

+1

你只能使用appendChild。你爲什麼要做所有這些事情? –

回答

2

_newNode是一個XML文檔。你不能直接在你的HTML中插入一個#document。 (否則,你得到這個錯誤:Uncaught HierarchyRequestError: Failed to execute 'insertBefore' on 'Node': Nodes of type '#document' may not be inserted inside nodes of type 'TBODY'.

嘗試使用

insertAfter(_newNode.childNodes[0], _referenceNode); 

因爲XML文檔的第一個孩子是你以後的元素。

此外,您的HTML無效。用途:

_newTR = "<tr><td>A very complex table</td><td>much more complex than in this example</td></tr>"; 

_newTR = "<tr><td>A very complex table<td></td><td>much more complex than in this example</td></tr>"; 
+0

感謝這對於像我這樣的新手知道XML文檔和節點之間的區別並不明顯。 – user310291

+0

@ user310291'console.log'是你的朋友。 – Hatchet

+0

問題在於console.log對於像我這樣的新手來說不夠明確。我還有另一個問題http://stackoverflow.com/questions/35759582/how-to-use-javascript-domparser-parsefromstring-on-complex-string – user310291