34

テーブルの要素th内にタグを挿入したい。実際に挿入している、の下に作成された行オブジェクトのメソッドを使用しています。JS ライブラリを使用しない JavaScript ソリューションはありますか?trtheadinsertCelltable.tHeadtd

更新現在、 Minko Gechevgaurav が提供するソリューションと同じものを使用しています。を使用するようなクリーンなソリューションがあるかどうか知りたいinsertCellですか?

4

4 に答える 4

36

最初に要求されたように、insertCell メソッドを使用することもできます。<td>insertCell メソッドによって作成されたものを上書きするように、outerHTML を変更するだけです。

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
于 2015-12-10T00:33:20.337 に答える
20

あなたはバニラJavaScriptでそれを行うことができます。これを試して:

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

于 2013-02-21T10:33:27.100 に答える
10

table.tHead.children[0].appendChild(document.createElement("th"))代わりにメソッドを使用してください。基本的にth、実行時にを作成し、それをtheadに挿入する必要があります。

于 2013-02-21T10:33:24.763 に答える
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 機能が使用されます。

document.querySelector("thead > tr").insertCell(); // inserts a th into a tr inside a thead
document.querySelector(":not(thead) > tr").insertCell(); // inserts a td into a tr not inside a thead

通常、ネイティブ オブジェクトを拡張することはお勧めできません。

于 2017-11-24T23:21:05.263 に答える