【问题标题】:How to replace in a Html `table`, the first `th` Html tag by `td` Html tag with JavaScript如何用 JavaScript 将 Html `table` 中的第一个`th` Html 标记替换为`td` Html 标记
【发布时间】:2014-03-06 13:55:52
【问题描述】:

我正在使用Filament Group, Inc. 的jQuery-Visualize 生成由HTML 表格元素驱动的HTML5 画布图表。

此插件的一个要求是,当使用多维表时,thead 行中的第一个 th tr 需要是 td。

我的表格如下所示:

<table>
    <thead>
        <tr>
            <th>...</th> <!--This element-->
            <th>...</th>
            <th>...</th>
            <th>...</th>
            <th>...</th>
            <th>...</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>...</th>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
        </tr>
        ...
    </tbody>
</table>

但是插件需要这个,否则它会在图表中添加一个额外的空分类,从而改变图表布局:

<table>
    <thead>
        <tr>
            <td>...</td><!--Needs to be-->
            <th>...</th>
            <th>...</th>
            <th>...</th>
            <th>...</th>
            <th>...</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>...</th>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
        </tr>
        ...
    </tbody>
</table>

我在 jsFiddle 上有一个示例,可以证明这个问题。

我怎样才能使用 Javascript/jQuery 来改变所描述的表格?

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

尝试使用:

$('tr th:eq(0)').replaceWith(function(){
    return $("<td />").append($(this).contents());
});

或更容易理解:

$('tr th:first').each(function() {
    $(this).replaceWith("<td>" + $(this).html() + "</td>");
});

【讨论】:

    【解决方案2】:

    你可以用喜欢

     $(document).ready(function () {
            $("th:first").replaceWith("<td/>",{text:"....."});
        });
    

    【讨论】:

      【解决方案3】:

      怎么样:

      $('tr>th').first().replaceWith('<td></td>');
      

      或者如果它不起作用:

      $('tr>th').first().replaceWith($('<td></td>'));
      

      【讨论】:

      • 你会得到空的 TD
      【解决方案4】:

      您可以使用 jQuery 来实现这一点。 试试这个代码:

      $(document).ready(function () {
         $("tr:first-child th").each(function() {
            $(this).replaceWith('<td>' + $(this).html() + '</td>'); 
         });
      });
      

      【讨论】:

      • 我会使用.html() 而不是.text()
      【解决方案5】:

      试试这个方法

      HTML 代码:

           <table id="Tbl">
            <tr>
             <th>Hello</th>
             <th>...</th>
             <th>...</th>
             <th>...</th>
             <th>...</th>
             <th>...</th>
            </tr>
          </table>
      

      JQUERY 代码:

          $('th:eq(0)').replaceWith('<td>'+$('th:eq(0)').html()+'</td>');
      

      现场演示:

      http://jsfiddle.net/dreamweiver/LPzs8/6/

      编辑:更正代码以使其更符合要求

      快乐编码:)

      【讨论】:

        猜你喜欢
        • 2017-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-24
        • 1970-01-01
        • 2014-04-08
        • 2022-01-23
        • 2011-01-07
        相关资源
        最近更新 更多