1

Здравствуйте! Есть таблица:

<tr class="tablesorter-headerRow" onclick="sortTable();">
    <!--<td data-column="0" class="tablesorter-header" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner"><input type = "checkbox" name = "lol"></input><i class="tablesorter-icon tablesorter-icon"></i></div></td>!-->
    <td data-column="0" class="tablesorter-header" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">№<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="1" class="tablesorter-header tablesorter-headerAsc primary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Cмс<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="2" class="tablesorter-header tablesorter-headerAsc secondary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Номеров<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="3" class="tablesorter-header tablesorter-headerAsc tertiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Время создания<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="4" class="tablesorter-header tablesorter-headerAsc fourtiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Периодичность<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="5" class="tablesorter-header tablesorter-headerAsc fivetiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Имя отправителя<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="6" class="tablesorter-header tablesorter-headerAsc sixtiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Сообщение<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="7" class="tablesorter-header tablesorter-headerAsc seventiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Начало отправки<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="8" class="tablesorter-header tablesorter-headerAsc eight" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Окончание отправки<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="9" class="tablesorter-header tablesorter-headerAsc nine" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Действие<i class="tablesorter-icon tablesorter-icon"></i></div></td>
</tr>

Нужно получить атрибут data-column столбца, на который нажали. Делаю так:

function sortTable()
{
    var attr = $(this).attr("data-column");
    alert(attr);
}

Выводит undefined. Что я делаю не так?

2 ответа 2

2

Используй подписку на всплытие:

$('table').on('click', 'td', function() {
  console.log($(this).data("column"));
});
<table>
  <tr class="tablesorter-headerRow">
    <td data-column="0" class="tablesorter-header" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">№<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="1" class="tablesorter-header tablesorter-headerAsc primary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Cмс<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="2" class="tablesorter-header tablesorter-headerAsc secondary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Номеров<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="3" class="tablesorter-header tablesorter-headerAsc tertiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Время создания<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="4" class="tablesorter-header tablesorter-headerAsc fourtiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Периодичность<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="5" class="tablesorter-header tablesorter-headerAsc fivetiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Имя отправителя<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="6" class="tablesorter-header tablesorter-headerAsc sixtiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Сообщение<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="7" class="tablesorter-header tablesorter-headerAsc seventiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Начало отправки<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="8" class="tablesorter-header tablesorter-headerAsc eight" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Окончание отправки<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="9" class="tablesorter-header tablesorter-headerAsc nine" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Действие<i class="tablesorter-icon tablesorter-icon"></i></div></td>
  </tr>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

1
  • а он точно атрибута значение берет? делаю <td data-column="255" class="tablesorter-header tablesorter-headerAsc primary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Cмс<i class="tablesorter-icon tablesorter-icon"></i></div></td> а он выдает 1 17 дек 2016 в 16:23
1
  1. Нужен атрибут ячейки, поэтому обрабатываем событие ячейки. Тогда $(this) укажет на нажатую ячейку.

$('td').click( function() {
  var attr = $(this).data("column");
  alert(attr);
})
<table>
  <tr class="tablesorter-headerRow">
    <td data-column="0" class="tablesorter-header" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">№<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="1" class="tablesorter-header tablesorter-headerAsc primary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Cмс<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="2" class="tablesorter-header tablesorter-headerAsc secondary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Номеров<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="3" class="tablesorter-header tablesorter-headerAsc tertiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Время создания<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="4" class="tablesorter-header tablesorter-headerAsc fourtiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Периодичность<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="5" class="tablesorter-header tablesorter-headerAsc fivetiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Имя отправителя<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="6" class="tablesorter-header tablesorter-headerAsc sixtiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Сообщение<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="7" class="tablesorter-header tablesorter-headerAsc seventiary" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Начало отправки<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="8" class="tablesorter-header tablesorter-headerAsc eight" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Окончание отправки<i class="tablesorter-icon tablesorter-icon"></i></div></td>
    <td data-column="9" class="tablesorter-header tablesorter-headerAsc nine" tabindex="0" unselectable="on" style="-webkit-user-select: none;"><div class="tablesorter-header-inner">Действие<i class="tablesorter-icon tablesorter-icon"></i></div></td>
  </tr>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

  1. Для атрибутов data-* у jQuery есть метод .data(). Кстати, он сам приводит значения этих атрибутов к типам данных Javascript.

  2. Консоль удобнее алертов. Она умеет подставлять значения в форматную строку, показывает свою историю и не заставляет жать OK по каждому случаю.

var total = 0;

$('table').click( function() {
  console.log( 'table %s', $(this).data("table") );
})

$('tr').click( function() {
  console.log( 'row %s', $(this).data("row") );
})

$('td').click( function() {
  var column = $(this).data("column");
  total += column;
  console.log( 'column %s, total %s', column, total );
})
td { padding: 3px 9px; }

table:hover { background: #ccc; }
tr:hover    { background: #999; }
td:hover    { background: #333; color: #fff; cursor: pointer; }
<table data-table="one">
  <tr data-row="first">
    <td data-column="1">1</td>
    <td data-column="2">2</td>
    <td data-column="3">3</td>
    <td data-column="4">4</td>
    <td data-column="5">5</td>
    <td data-column="6">6</td>
    <td data-column="7">7</td>
  </tr>
  <tr data-row="second">
    <td data-column="1">1</td>
    <td data-column="2">2</td>
    <td data-column="3">3</td>
    <td data-column="4">4</td>
    <td data-column="5">5</td>
    <td data-column="6">6</td>
    <td data-column="7">7</td>
  </tr>
</table>
<table data-table="two">
  <tr data-row="first">
    <td data-column="1">1</td>
    <td data-column="2">2</td>
    <td data-column="3">3</td>
    <td data-column="4">4</td>
    <td data-column="5">5</td>
    <td data-column="6">6</td>
    <td data-column="7">7</td>
  </tr>
  <tr data-row="second">
    <td data-column="1">1</td>
    <td data-column="2">2</td>
    <td data-column="3">3</td>
    <td data-column="4">4</td>
    <td data-column="5">5</td>
    <td data-column="6">6</td>
    <td data-column="7">7</td>
  </tr>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

5
  • "поэтому обрабатываем событие ячейки" - брррррр.. Не, так не надо.
    – Qwertiy
    17 дек 2016 в 5:32
  • @Qwertiy Добавьте, пожалуйста, пару слов, почему и как лучше? 17 дек 2016 в 5:46
  • 1
    Я вроде в ответе написал. А лучше потому что там обработчик получается только один и он сможет работать с динамически добавляемыми строками без дополнительных усилий.
    – Qwertiy
    17 дек 2016 в 5:54
  • @Qwertiy Спасибо. Вот ещё об отличиях между .click() и .on() (на английском). 17 дек 2016 в 6:25
  • 1
    Вообще-то click - это просто обёртка над on.
    – Qwertiy
    17 дек 2016 в 14:48

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.