优化响应表javascript

时间:2017-05-31 20:04:23

标签: javascript html responsive-design

Codepen example

所以我写了一些javascript,以便在较小的设备上对每个表格单元格进行正常的表格显示。我想优化我的代码并使其更好。任何人都有任何建议。 javascript如下,你可以在我的代码笔上找到工作示例。

    function grabTable(){

  /* grab all tables with responsive-table class then add the th to the tbody cells as a data attribute */
    var responsiveTables = document.getElementsByClassName("responsive-table");
    if(responsiveTables.length !== 0){
    var dataArray = [];

    for (var r = 0; r < responsiveTables.length;  r++) {
    /* clears array for next loop */
    dataArray = [];

    var datalables = responsiveTables[r].getElementsByTagName("th");

    if(datalables.length == 0){
    var firstrow = responsiveTables[r].getElementsByTagName("tr"); 
    datalables = firstrow[0].getElementsByTagName("td");
    firstrow[0].className = "hideLabels";
    }

    /* cleans html values so they don't look funny when added*/
    for(var i=0; i<datalables.length; i++){
      var dirtyData = datalables[i].innerHTML;
      var cleanData = dirtyData.replace(/(<([^>]+)>)/ig,"");
      dataArray[i] = cleanData;
    }

      var row = responsiveTables[r].getElementsByTagName("tr"); 

        for (var m = 0; m < row.length;  m++) {

          /*sets data-label on table, which css makes viewable.*/
          var col = row[m].getElementsByTagName("td");
            if(col.length === dataArray.length){
                for (var j = 0; j <col.length; j++) {
                  col[j].setAttribute("data-label", dataArray[j]);
                  }
              }
              else if(col.length !== dataArray.length  && col.length > 0){
                  console.log(col);
                  for (var p = 0; p <col.length; p++) {
                  col[p].className = "fullrow";
                  }
              }
        }
   }
   }
   else{
    //console.log("no responsive tables on page");
   } 
}
grabTable();

0 个答案:

没有答案