Javascript data th JS每页只工作一次

Javascript data th JS每页只工作一次,javascript,html,css,Javascript,Html,Css,我正在使用此代码笔中的代码使我的表格响应: 我的站点上的所有内容都像他的示例中那样工作,但是我想在页面中添加多个表。当我这样做时,只有页面上的第一个表得到了浏览器变小时添加到其中的“data th=”,其余的表是空白的。我希望它被添加到页面上的所有表头中,但不确定如何更改他的代码来完成它 我更改了一些类,因此下面是我的代码(为了节省空间而缩减表): 响应表的JS var headertext=[], headers=document.queryselectoral(“.responsive th

我正在使用此代码笔中的代码使我的表格响应:

我的站点上的所有内容都像他的示例中那样工作,但是我想在页面中添加多个表。当我这样做时,只有页面上的第一个表得到了浏览器变小时添加到其中的“data th=”,其余的表是空白的。我希望它被添加到页面上的所有表头中,但不确定如何更改他的代码来完成它

我更改了一些类,因此下面是我的代码(为了节省空间而缩减表):

响应表的JS var headertext=[], headers=document.queryselectoral(“.responsive th”), tablerows=document.queryselectoral(“.th”), tablebody=document.querySelector(“.responsivetbody”); 对于(变量i=0;i HTML

<table class="responsive mesh">
<thead>
<tr>
<th>Phifer</th>
<th>Openness</th>
<th>Sun/UV</th>
<th>Protection</th>
<th>Sample</th>
</tr>
</thead>
<tbody>
<tr>
<td>18/14 - Charcoal</td>
<td>58%</td>
<td>Up To 40%</td>
<td>Blockage</td>
<td><img src="http://minnesotascreens.cloudaccess.host/wp-content/uploads/2015/03/mesh_1814_charcoal.jpg" alt="mesh_1814_charcoal" class="alignnone size-full wp-image-227" /></td>
</tr>
</tbody>
</table>

<hr/>

<table class="responsive mesh">
<thead>
<tr>
<th>Phifer 20/30</th>
<th>Openness</th>
<th>Sun/UV</th>
<th>Protection</th>
<th>Sample</th>
</tr>
</thead>
<tbody>
<tr>
<td>Charcoal</td>
<td>32%</td>
<td>Up To 65%</td>
<td>Blockage</td>
<td><img src="http://minnesotascreens.cloudaccess.host/wp-content/uploads/2015/03/mesh_2030_charcoal.jpg" alt="mesh_2030_charcoal" class="alignnone size-full wp-image-236" /></td>
</tr>
</tbody>
</table>

菲弗
开放性
阳光/紫外线
保护
样品
18/14-木炭
58%
高达40%
堵塞

菲弗20/30 开放性 阳光/紫外线 保护 样品 木炭 32% 高达65% 堵塞

我的站点:

您需要迭代所有表,然后迭代每个表中的所有行和单元格。试着这样做:

var tables = document.querySelectorAll(".responsive"),
    tbody, headers, headertext, i, j, k;

for (i = 0; i < tables.length; i++) {

    tbody = tables[i].tBodies[0];
    headers = tables[i].tHead.rows[0].children;
    headertext = [];

    for (j = 0; j < headers.length; j++) {
        headertext.push(headers[j].textContent.trim());
    }

    for (j = 0; j < tbody.rows.length; j++) {
        for (k = 0; k < tbody.rows[j].cells.length; k++) {
            tbody.rows[j].cells[k].setAttribute("data-th", headertext[k]);
        }
    }    
}
var tables=document.querySelectorAll(“.responsive”),
t正文,标题,标题文本,i,j,k;
对于(i=0;i

演示:

我假设“querySelectorAll”可以全部获得,但JS还不太好。完全有效!非常感谢。
var tables = document.querySelectorAll(".responsive"),
    tbody, headers, headertext, i, j, k;

for (i = 0; i < tables.length; i++) {

    tbody = tables[i].tBodies[0];
    headers = tables[i].tHead.rows[0].children;
    headertext = [];

    for (j = 0; j < headers.length; j++) {
        headertext.push(headers[j].textContent.trim());
    }

    for (j = 0; j < tbody.rows.length; j++) {
        for (k = 0; k < tbody.rows[j].cells.length; k++) {
            tbody.rows[j].cells[k].setAttribute("data-th", headertext[k]);
        }
    }    
}