簡體   English   中英

data-th JS每頁只能運行一次

[英]data-th JS only works once per page

我使用此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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM