事实:我没有jQuery经验或知识,这是我有关Stack Overflow的第一个问题。

需要:我正在使用Bootstrap 3.3.6建立一个网站,其中包含多个非常复杂的数据表,这些表必须通过CSS动态地堆叠在移动设备上。列标题必须重复,否则td值没有意义。由于该网站是双语网站,因此我想控制移动td header 中的内容。

解决方案:一个jQuery函数,该函数将自定义 header (通过每个表的第一行的title属性输入)存储在数组中,然后通过CSS content属性将其添加到tbody中的每个td。

问题:上述功能运行良好..除非文档中有多个表。然后,该功能将FIRST表中的标题应用于文档中的ALL表。

我想要的是: 1)仅将需要应用上述功能的表赋予唯一的id属性。 2)没有id属性的表应被忽略。 3)然后,该函数必须检索每个唯一表的标题并将其应用于每个相应的表主体。 4)我是否担心此功能可能会干扰其他脚本,例如Modernizr或prettyPhoto?

JSFiddle:what I have so far

(function() {
    "use strict";
    var tableIds = Array();
    $('table').each(function(tid) {
        if (tableIds) {
            tableIds[tid] = $(this).attr('id');
        }
        var currentId = tableIds[tid];
        alert('Id is: ' + currentId);
    });

    var header = Array();
    /*get titles from the headings*/
    $('thead tr:first-child th').each(function(i) {
        if (header) {
            header[i] = $(this).attr('title');
        }
    });
    /*loop through tbody rows and apply headings to each td*/
    $('tbody tr').each(function() {
        var thRow = $(this);
        thRow.find('td').each(function(j) {
            $(this).attr('title', header[j]);
        });
    });
}());

最佳答案

假设您的表结构类似于下面给出的表,则只需将一个类applyHeader分配给要应用标题的表

<u>Table1</u>
<table class="applyHeader">
  <thead>
    <tr>
      <th title="header11">header1</th>
      <th title="header12">header2</th>
      <th title="header13">header3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>col11</td>
      <td>col12</td>
      <td>col13</td>
    </tr>
  </tbody>
</table>
<br>
<u>Table2</u>
<table class="applyHeader">
  <thead>
    <tr>
      <th title="header21">header1</th>
      <th title="header22">header2</th>
      <th title="header23">header3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>col21</td>
      <td>col22</td>
      <td>col23</td>
    </tr>
  </tbody>
</table>
<br>
<u>Table3</u>
<table >
  <thead>
    <tr>
      <th title="header31">header1</th>
      <th title="header32">header2</th>
      <th title="header33">header3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>col31</td>
      <td>col32</td>
      <td>col33</td>
    </tr>
  </tbody>
</table>

使用以下功能获得所需的结果
   (function() {
      "use strict";
      $('table.applyHeader').each(function() {
          var tableSelected=this;
      $(this).find('th').each(function(index) {
       var headerTitle = $(this).attr('title');
       $(tableSelected).find('tbody').find('td').eq(index).attr('title',headerTitle);
      });
      });

  }());

编辑1:-Jsfiddle Demo Link

10-07 19:14
查看更多