如何阻止jQuery函数(读取thead的第1行的标题属性)将检索到的标题应用于文档中的所有表?

Mar*_*kaT 9 javascript css jquery html5

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

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

解决方案:一个jQuery函数,它存储自定义标头 - 通过每个表的第一行中的title属性输入 - 在一个数组中,然后通过CSS content属性添加到tbody中的每个td.

问题:上面的函数运行良好..除非文档中有多个表.然后,该函数将FIRST表中的标题应用于文档中的所有表.

我想要的: 1)只为需要应用上述功能的表提供唯一的id属性. 2)应忽略没有id属性的表. 3)然后,该函数必须检索每个唯一表的标题并将其应用于每个相应的表tbody. 4)我担心这个功能可能会干扰任何其他脚本,例如Modernizr或prettyPhoto?

JSFiddle:到目前为止我所拥有的

(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]);
        });
    });
}());
Run Code Online (Sandbox Code Playgroud)

Ata*_*ore 6

假设您的表结构类似于下面给出的表,那么只需将类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>
Run Code Online (Sandbox Code Playgroud)

使用以下函数获取所需的结果

   (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);
      });
      });

  }());
Run Code Online (Sandbox Code Playgroud)

编辑1: - Jsfiddle演示链接

  • 看到Js小提琴链接https://jsfiddle.net/7a8bk1s0/2/你可以为不同的表保持不同的ID,但也将类附加到你想要应用标题的那些表 (2认同)