如何将响应表函数应用于由ajax加载的表?

时间:2015-11-07 22:39:31

标签: jquery zurb-foundation responsiveness

我有一个小脚本,在屏幕调整大小时应用基础响应表css,效果很好。问题是如果一个表被加载到页面的VIA ajax,脚本将不会在移动设备上运行,因为屏幕永远不会调整大小。

这是脚本:

jQuery(document).ready(function() {


  var switched = false;
  var updateTables = function() {
    if ((jQuery(window).width() < 767) && !switched ){
      console.log('reconfig table');
      switched = true;
      jQuery("table.responsive").each(function(i, element) {
        splitTable(jQuery(element));
      });
      jQuery('.scrollable.scroll-right').scrollLeft(10000);
      return true;
    }
    else if (switched && (jQuery(window).width() > 767)) {
      switched = false;
      jQuery("table.responsive").each(function(i, element) {
        unsplitTable(jQuery(element));
      });
    }

    jQuery('.scrollable.scroll-right').scrollLeft(10000);


  };

  jQuery(window).load(updateTables);
  jQuery(window).on("redraw",function(){switched=false;updateTables();}); // An event to listen for
  jQuery(window).on("resize", updateTables);


    function splitTable(original)
    {
      var wrapperClass = '';
      var classnames = jQuery('table.responsive').attr('data-scrollbar-position');
      if(classnames == 'left'){
        wrapperClass = 'scroll-right';
      }


      original.wrap("<div class='table-wrapper' />");

        var copy = original.clone();
        copy.find("td:not(:first-child), th:not(:first-child)").css("display", "none");
        copy.removeClass("responsive");

        original.closest(".table-wrapper").append(copy);
        copy.wrap("<div class='pinned' />");
        original.wrap("<div class='scrollable " + wrapperClass + "' />");

    setCellHeights(original, copy);
    }

    function unsplitTable(original) {
    original.closest(".table-wrapper").find(".pinned").remove();
    original.unwrap();
    original.unwrap();
    }

  function setCellHeights(original, copy) {
    var tr = original.find('tr'),
        tr_copy = copy.find('tr'),
        heights = [];

    tr.each(function (index) {
      var self = jQuery(this),
          tx = self.find('th, td');

      tx.each(function () {
        var height = jQuery(this).outerHeight(true);
        heights[index] = heights[index] || 0;
        if (height > heights[index]) heights[index] = height;
      });

    });

    tr_copy.each(function (index) {
      jQuery(this).height(heights[index]);
    });
  }

});

如何将此应用于移动设备?

1 个答案:

答案 0 :(得分:1)

使用AJAX加载新内容后,请运行

jQuery(window).resize();

这会触发resize事件并重绘。