2013-02-21 70 views
20

我想在表格的thead元素的tr內插入th標籤。我在table.tHead下創建的行對象的方法使用insertCell,它實際上是插入td。有沒有沒有使用任何JS庫的JavaScript解決方案?在th中插入th

更新 目前我使用的東西一樣通過Minko Gechevgaurav提供解決方案。我想知道是否有任何干淨的解決方案,如使用insertCell

+1

被告知,'th'作爲直接子'thead'是無效的,並可能導致事與願違的結果在不同的瀏覽器。有效的佈局是這樣的:'table-> thead-> tr-> th' – 2013-02-21 10:37:00

+0

對不起,我的壞,我的意思是'th'裏面的tr。 – 2013-02-21 10:44:24

+0

我在'thead'裏面用'tr'修復了我的問題:-) – 2013-02-21 10:58:50

回答

10

你可以用vanilla做到這一點。試試這個:

HTML

<table id="table"> 
    <thead> 
    <tr> 
     <th>First</th> 
    </tr> 
    <thead> 
</table> 

的JavaScript

var tr = document.getElementById('table').tHead.children[0], 
    th = document.createElement('th'); 
th.innerHTML = "Second"; 
tr.appendChild(th); 

下面是一個例子http://codepen.io/anon/pen/Bgwuf

7

改爲使用table.tHead.children[0].appendChild(document.createElement("th"))方法。基本上你必須在運行時創建一個th並將其插入到你的遊戲中。

16

您還可以使用的insertCell方法最初請求。你只需要改變outerHTML覆蓋由的insertCell方法創建的<td>

var table = document.createElement("TABLE") 
var row = table.insertRow(0); 
    row.insertCell(0).outerHTML = "<th>First</th>"; // rather than innerHTML 

要匹配給定的例子:

HTML

<table id="table"> 
    <thead> 
    <tr> 
     <th>First</th> 
    </tr> 
    <thead> 
</table> 

的Javascript

var tr = document.getElementById('table').tHead.children[0]; 
    tr.insertCell(1).outerHTML = "<th>Second</th>" // some browsers require the index parm -- 1 
+0

非常適用於Chrome和Firefox,但設置outerHtml不會對IE 6 – 2017-02-27 02:07:11

+0

工作,這是我怎麼能在標題行('tr')在影響新標題單元格('th')的位置的唯一途徑? – kabeleced 2017-08-09 06:29:18

0

你可以通過改變它的原型添加此功能,本機HTMLTableRowElement:此代碼運行

HTMLTableRowElement.prototype.insertCell = (function(oldInsertCell) { 
    return function(index) { 
     if (this.parentElement.tagName.toUpperCase() == "THEAD") { 
      if (index < -1 || index > this.cells.length) { 
       // This case is suppose to throw a DOMException, but we can't construct one 
       // Just let the real function do it. 
      } else { 
       let th = document.createElement("TH"); 
       if (arguments.length == 0 || index == -1 || index == this.cells.length) { 
        return this.appendChild(th); 
       } else { 
        return this.insertBefore(th, this.children[index]); 
       } 
      } 
     } 
     return oldInsertCell.apply(this, arguments); 
    } 
})(HTMLTableRowElement.prototype.insertCell); 

後,任何新的HTMLTableRowElements(「TD」標籤)將檢查如果父是THEAD標記。如果是這樣,它將執行與insertCell相同的功能,但使用th標記。如果不是,它將只使用原始的insertCell功能。

注意it is generally not recommended to extend the native objects.