javascript - data-th JS 每页只工作一次

标签 javascript html css

我正在使用此 CodePen 中的代码来使我的表格响应:http://codepen.io/anon/pen/myayee

我网站上的所有内容都按照他的示例运行,但是我想向页面添加多个表格。当我这样做时,当浏览器变小时,只有页面上的第一个表格会添加“data-th=”,其余表格都是空白的。我希望将它添加到页面上的所有表标题中,但不确定如何更改他的代码来完成它。

我更改了一些类,所以这是我的代码(为了节省空间而减少了表格):

//JS FOR RESPONSIVE TABLES
var headertext = [],
headers = document.querySelectorAll(".responsive th"),
tablerows = document.querySelectorAll(".responsive th"),
tablebody = document.querySelector(".responsive tbody");

for(var i = 0; i < headers.length; i++) {
  var current = headers[i];
  headertext.push(current.textContent.replace(/\r?\n|\r/,""));
} 
for (var i = 0, row; row = tablebody.rows[i]; i++) {
  for (var j = 0, col; col = row.cells[j]; j++) {
    col.setAttribute("data-th", headertext[j]);
  } 
}

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>

我的网站:http://minnesotascreens.cloudaccess.host/products/phantom-retractable-door-screens/

最佳答案

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

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

演示: http://jsfiddle.net/6kkb3369/

关于javascript - data-th JS 每页只工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29171613/

相关文章:

javascript - 文本及其下拉列表不在一行中

javascript - 如何将指向外部营销视频的链接添加到站点主页?

javascript - 为什么 jQuery 不能在 IE11 中运行

html - 展开动态背景

javascript - HTML 重复 ID

html - 背景图像 1px 偏移

javascript - 输入焦点时隐藏 ios 设备上的键盘

html - 使用 div 创建垂直条

javascript - 如何将一张图像分成 9 个小图像(类似于拼图)

javascript - 未捕获的类型错误 : Object [object Object] has no method 'wipetouch'