在 jquery 中获取 TH 值

Sag*_*gar 0 javascript jquery

我正在尝试获取数组中的标题文本,但是通过以下操作,我得到了值加上 th 标签,即[<th>value1</th>, <th>value2</th>],我想获取[value1, value2].

$('#header').children().each(function(){this.html});
Run Code Online (Sandbox Code Playgroud)

这是我的 HTML 的样子:

<tr bgcolor="#cdb79e" id="header">
    <th>Origin Code</th>
    <th>Description</th>
    <th>Notes</th>
    <th>Domain</th>
    <th>Tier</th>
    <th>Engine</th>
    <th>Network</th>
    <th>Platform</th>
    <th>Expansion Tool</th>
    <th>Date</th>
    <th>Imps</th>
    <th>Clicks</th>
    <th>Engine CTR</th>
    <th>Average Position</th>
    <th>Picks</th>
    <th>LP CTR</th>
    <th>GSL Picks</th>
    <th>GSL LP CTR</th>
    <th>Merchant Picks</th>
    <th>Merchant LP CTR</th>
    <th>CPC</th>
    <th>RPC</th>
    <th>RPP</th>
    <th>Cost</th>
    <th>Total Rev</th>
    <th>Margin</th>
    <th>ROI</th>
</tr>
Run Code Online (Sandbox Code Playgroud)

小智 5

假设您的 HTML 看起来像这样:

<table>
    <thead>
        <tr id='header'>
            <th>Value1</th>
            <th>Value2</th>
        </tr>
    </thead>
</table>
Run Code Online (Sandbox Code Playgroud)

您可以使用这样的东西来构建<th>元素文本的数组:

var headerArray = [];
$('#header').children().each(function(){
    headerArray.push($(this).text());
});
console.log(headerArray);
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用 `map` 而不是 `each`,它具有更清晰的语法 IMO。`$('#header').children().map(function(){return this.innerHTML;})` (2认同)