Исключите столбец из того, чтобы быть отсортированным с помощью jQuery tablesorter

По моему опыту это лучше всего работает с помощью аннотации . Таким образом, вы избегаете странного перекоса, с которым вы сталкиваетесь с ax.arrow, который каким-то образом трудно контролировать.

EDIT: Я включил его в небольшую функцию.

from matplotlib import pyplot as plt
import numpy as np


def add_arrow(line, position=None, direction='right', size=15, color=None):
    """
    add an arrow to a line.

    line:       Line2D object
    position:   x-position of the arrow. If None, mean of xdata is taken
    direction:  'left' or 'right'
    size:       size of the arrow in fontsize points
    color:      if None, line color is taken.
    """
    if color is None:
        color = line.get_color()

    xdata = line.get_xdata()
    ydata = line.get_ydata()

    if position is None:
        position = xdata.mean()
    # find closest index
    start_ind = np.argmin(np.absolute(xdata - position))
    if direction == 'right':
        end_ind = start_ind + 1
    else:
        end_ind = start_ind - 1

    line.axes.annotate('',
        xytext=(xdata[start_ind], ydata[start_ind]),
        xy=(xdata[end_ind], ydata[end_ind]),
        arrowprops=dict(arrowstyle="->", color=color),
        size=size
    )


t = np.linspace(-2, 2, 100)
y = np.sin(t)
# return the handle of the line
line = plt.plot(t, y)[0]

add_arrow(line)

plt.show()

Это не очень интуитивно, но он работает. Затем вы можете играть в словаре arrowprops, пока он не будет выглядеть правильно.

16
задан Chad Birch 12 January 2009 в 22:37
поделиться

3 ответа

Вот виджет, который можно использовать, который выполнит то, что Вы ищете:

$(function() {
    // add new widget called indexFirstColumn
    $.tablesorter.addWidget({
        // give the widget a id
        id: "indexFirstColumn",
        // format is called when the on init and when a sorting has finished
        format: function(table) {               
            // loop all tr elements and set the value for the first column  
            for(var i=0; i < table.tBodies[0].rows.length; i++) {
                $("tbody tr:eq(" + i + ") td:first",table).html(i+1);
            }                                   
        }
    });

    $("table").tablesorter({
        widgets: ['zebra','indexFirstColumn']
    });

});
18
ответ дан 30 November 2019 в 15:18
поделиться

Редактирование: я сделал образец этой техники в http://jsbin.com/igupu4/3 . Нажмите любой заголовок столбца к виду...

, В то время как у меня нет ответа на Ваш вопрос о jQuery, вот альтернативный способ получить определенное поведение, которое Вы описали здесь, зафиксированные номера строк после сортировки. (Используя CSS, конкретно свойство содержания, и связанные со счетчиком свойства/функции .)

<html>
<head>
  <title>test</title>
  <style type="text/css">
    tbody tr 
    {
      counter-increment : rownum ; 
    }
    tbody 
    { 
      counter-reset: rownum; 
    }
    table#sample1 td:first-child:before 
    { 
      content: counter(rownum) " " ; 
    }
    table#sample2 td.rownums:before 
    { 
      content: counter(rownum) ; 
    }
  </style>
  <script src="jquery-1.2.6.min.js" ></script>
  <script src="jquery.tablesorter.min.js" ></script>
  <script>
    $(document).ready(function() 
      { 
        $("table").tablesorter(); 
      } 
    ); 
  </script>
</head>

<body>
  <table id="sample1">
    <thead>
      <tr>
        <th>Col 1</th>
        <th>Col 2</th>
    </thead>
    <tbody>
      <tr>
        <td>
          <p>foo</p>
        </td>
        <td>
          <p>quuz</p>
        </td>
      </tr>

      <tr>
        <td>bar</td>
        <td>quux</td>
      </tr>

      <tr>
        <td>baz</td>
        <td>baz</td>
      </tr>
    </tbody>
  </table>

  <table id="sample2">
    <thead>
      <tr>
        <th>Rownums</th>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>More Rownums</th>
    </thead>
    <tbody>
      <tr>
        <td class="rownums"></td>
        <td>
          <p>foo</p>
        </td>
        <td>
          <p>bar</p>
        </td>
        <td class="rownums"></td>
      </tr>

      <tr>
        <td class="rownums"></td>
        <td>quuz</td>
        <td>baz</td>
        <td class="rownums"></td>
      </tr>

      <tr>
        <td class="rownums"></td>
        <td>fred</td>
        <td>quux</td>
        <td class="rownums"></td>
      </tr>
    </tbody>
  </table>
</body>
</html>

, Если Вашим браузером является достаточно совместимый CSS2.1, можно использовать tr:before вместо td:first-child:before в демонстрационном 1. ( Mozilla только поддерживает это в соединительной линии на данный момент... )

В демонстрационных 2, Вы видите, как расположить Ваши столбцы номера строки где угодно, не только в первом столбце.

4
ответ дан 30 November 2019 в 15:18
поделиться

Hrm. Из метода tablesorter реорганизации таблицы я вполне уверен, что это не совершенно возможно. Tablesorter вытя каждый TR из DOM один за другим и видов их на основе индексируемого поля, повторно вставляя весь TR, не изменяя содержание TR всегда. Ваше требуемое решение должно было бы тогда выполнить итерации назад через таблицу после каждого вида и повторно перечислить первый столбец. Tablesorter действительно имеет сменный метод, который используется zebrastripe и другими расширениями. Возможно, это могло использоваться для сцепления методов сортировки?

0
ответ дан 30 November 2019 в 15:18
поделиться
Другие вопросы по тегам:

Похожие вопросы: