1

Есть таблица, которая заполняется через PHP:

<table id="position">
  <thead>
    <tr>
      <th scope="col">ID</th>
      <th scope="col">Статус</th>
      <th scope="col">IP-адрес</th>
      <th scope="col">Последняя активность</th>
      <th scope="col"></th>
    </tr>
  </thead>
  <tbody>
    <tr id='{$ip}'>
      <th scope='row'>{$id}</th>
      <td>{$online}</td>
      <td><a href='http://{$ip}' target='_blank'>{$ip}</a></td>
      <td>{$lastActive}</td>
      <td id='button'><i class='bi bi-trash' style='font-size: 20px' ;></i></td>
    </tr>";
  </tbody>
</table>

Есть отслеживание нажатия по строке таблицы:

const tbody = document.querySelector('#position tbody');
tbody.addEventListener('click', function (e) {
const cell = e.target.closest('td');
if (!cell) {return;} // Quit, not clicked on a cell
const row = cell.parentElement;
console.log(row.rowIndex, row.id);

Проблема в том, что функция отслеживает клик по всей строке таблицы, а мне нужно только по последней ячейке (с id='button'). Пробовал несколько вариантов - ничего не помогло - отслеживалась только ячейка первой строки, остальные игнорировались.

2 ответа 2

1

Просто уточните селектор в closest() :

const tbody = document.querySelector('#position tbody');
tbody.addEventListener('click', function(e) {
  const cell = e.target.closest('td:last-child');
  if (!cell) {
    return;
  } // Quit, not clicked on a cell
  const row = cell.parentElement;
  console.log(row.rowIndex, row.id);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="position">
  <thead>
    <tr>
      <th scope="col">ID</th>
      <th scope="col">Статус</th>
      <th scope="col">IP-адрес</th>
      <th scope="col">Последняя активность</th>
      <th scope="col">button</th>
    </tr>
  </thead>
  <tbody>
    <tr id='{$ip}'>
      <th scope='row'>{$id}</th>
      <td>{$online}</td>
      <td><a href='http://{$ip}' target='_blank'>{$ip}</a></td>
      <td>{$lastActive}</td>
      <td id='button'><i class='bi bi-trash' style='font-size: 20px'>button</i></td>
    </tr>
  </tbody>
</table>

1
  • 1
    Всё, сработало, спасибо большое)
    – Arteil
    9 дек 2021 в 8:00
0

как-то не нормально отслеживать клики на ячейке целиком. Добавьте внутрть кнопку или ссылку, и к ней прицепите клик.

<td>
   <a href="#" class="remove">
     <i class='bi bi-trash' style='font-size: 20px';></i>
   </a>
</td>

и jquery (раз уж есть в тегах)

$(".remove").click(function(e){
    e.preventDefault();
    $(this).closest('tr').remove();
});

если строки добавляются динамически то добавьте идентификатор к tbody

$("tbody#rows").on('click', '.remove', function(){....});

Если уж надо сделать таки клики прямо в ячейки, то класс .remove переносите в сам <td>, в остальном код не изменится.

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

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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