Как написать JavaScript, который создает фиксированный заголовок для каждой таблицы в отдельности - PullRequest
1 голос

На WordPress есть собственный сайт Тарифы . Я создал скрипт, который ищет каждую копию таблицы thead и фиксирует ее в таблице fixed_table_header, но вот проблема, когда тот же shortcode создает новую таблицу для каждой и тот же thead, поможет разобраться, как добавить или изменить скрипт, чтобы заголовок был исправлен для каждой таблицы отдельно

<?php    
    /*====================================================SHORTCODES EXEL=========================================================*/
        public function show_mps_excel($atts){

            $atts = shortcode_atts( array(
                'name' => 'express_import',
                'sheet' => 0,
                'class' => '',
            ), $atts );

            extract($atts);
            ?>
<?php  $mps_option = get_option('gamma_mps'); ?>
<?php if(isset($mps_option[$name]['sheet'.$sheet])): ?>
<?php ob_start(); ?>
<div class="container-fluid block-content">
  <div class="row">
    <div class="col-sm-12 col-md-12 col-lg-12 welcome-text">
      <!-- <table class="table table-hover table-bordered taxes" style="margin-top: -25px"> -->
      <?php if($name != 'zones'): ?>
      <?php $this->full_table($mps_option, $name, $sheet, $class); ?>
      <?php else: ?>
      <?php $this->half_table($mps_option, $name, $sheet, $class, 0, 118); ?>
      <?php $this->half_table($mps_option, $name, $sheet, $class, 117, 234); ?>
      <?php endif; ?>

      <?php if(false): ?>
      <h5>Загрузить таблицу в .XLSX: <a class="btn btn-success" href="<?php echo $mps_option[$name]['download_url']; ?>">Загрузить</a></h5>
      <?php endif; ?>
    </div>
  </div>
</div>
<?php $html = ob_get_clean(); ?>
<?php endif; ?>
<?php
            return $html;
        }
        private function full_table($mps_option, $name, $sheet, $class){
            ?>
  <table class="table table-hover table-bordered mps_xls sheet-<?php echo $sheet; ?> <?php echo $name; ?> <?php echo $class; ?>" style="margin-top: -25px">
    <?php foreach ($mps_option[$name]['sheet'.$sheet] as $row => $cols): ?>
    <?php if(!$cols['A'] && !$cols['B'] && !$cols['C']) continue; ?>
    <?php echo $row==1 ? '<thead><tr>':'<tr>'; ?>
    <?php foreach ($cols as $col): ?>
    <?php echo $row==1 ? '<th>':'<td>'; ?>
    <?php echo $col; ?>
    <?php echo $row==1 ? '</th>':'</td>'; ?>
    <?php endforeach; ?>
    <?php echo $row==1 ? '</tr></thead>':'</tr>'; ?>
    <?php endforeach; ?>
    </tbody>
  </table>
  <?php
        }
        private function half_table($mps_option, $name, $sheet, $class, $start_row, $end_row){
            $count = 1;
            ?>
    <div class="col-sm-6 col-md-6 col-lg-6 welcome-text">
      <table class="table table-hover table-bordered mps_xls sheet-<?php echo $sheet; ?> <?php echo $name; ?> <?php echo $class; ?>" style="margin-top: -25px">
        <?php foreach ($mps_option[$name]['sheet'.$sheet] as $row => $cols): ?>
        <?php if($count <= $start_row && $count > 1) {$count++; continue;} ?>
        <?php if($count >= $end_row) break; ?>
        <?php echo $row==1 ? '<thead><tr>':'<tr>'; ?>
        <?php foreach ($cols as $col): ?>
        <?php echo $row==1 ? '<th>':'<td>'; ?>
        <?php echo $col; ?>
        <?php echo $row==1 ? '</th>':'</td>'; ?>
        <?php endforeach; ?>
        <?php echo $row==1 ? '</tr></thead>':'</tr>'; ?>
        <?php $count++; ?>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php
        }
    }
    ?>
(function($) {
  $(document).ready(function() {

    var table = $('table'),
      thead = table.find('thead'),

      fixed_thead,
      fixed_table = $('<table />', {
        'cellpadding': 5,
        'cellspacing': 0,
        'border': 1,
        'id': 'fixed_table_header'
      }),

      fixed_table_wrapper = $('<div />', {
        'height': 400,
        'css': {
          'overflow': 'auto'
        }
      });

    table.before(fixed_table);

    thead.find('td').each(function() {
      $(this).css('width', $(this).width());
    });

    fixed_thead = thead.clone();
    fixed_table.append(fixed_thead);

    thead.hide();

    table.wrap(fixed_table_wrapper);

    // align the new table header with the original table
    fixed_table.css('left', (fixed_table.offset().left - table.offset().left) * -1);
  });

})(jQuery);

1 Ответ

0 голосов
/ 13 мая 2019

Если я правильно понимаю ваш вопрос, вы нацеливаетесь только на первую таблицу, используя var table = $('table'),.Вам нужно запустить манипуляции на каждый table, чтобы ваш код выглядел примерно так:

(function($) {
  $(document).ready(function() {
    $('table').each(function() {
      var table = $(this),
        thead = table.find('thead'),

        fixed_thead,
        fixed_table = $('<table />', {
          'cellpadding': 5,
          'cellspacing': 0,
          'border': 1,
          'id': 'fixed_table_header'
        }),

        fixed_table_wrapper = $('<div />', {
          'height': 400,
          'css': {
            'overflow': 'auto'
          }
        });

      table.before(fixed_table);

      thead.find('td').each(function() {
        $(this).css('width', $(this).width());
      });

      fixed_thead = thead.clone();
      fixed_table.append(fixed_thead);

      thead.hide();

      table.wrap(fixed_table_wrapper);

      // align the new table header with the original table
      fixed_table.css('left', (fixed_table.offset().left - table.offset().left) * -1);
    });
  });
})(jQuery);

Этот случай аналогичен тому, как должен быть написан плагин jQuery, и решениетоже похоже: https://learn.jquery.com/plugins/basic-plugin-creation/#using-the-each-method

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...