как сделать bootstrap таблицу кликабельной - PullRequest
0 голосов
/ 18 февраля 2020

У меня есть bootstrap, как это в основном. html страница:

<table class="table table-striped">
 <thead>
    <tr>
     <th scope="col">#</th>
     <th scope="col">First</th>
     <th scope="col">Last</th>
     <th scope="col">Handle</th>
   </tr>
 </thead>
 <tbody>
  <tr>
    <th scope="row">1</th>
    <td>Mark</td>
    <td>Otto</td>
    <td>@mdo</td>
 </tr>
 <tr>
   <th scope="row">2</th>
   <td>Jacob</td>
   <td>Thornton</td>
   <td>@fat</td>
</tr>
<tr>
  <th scope="row">3</th>
  <td>Larry</td>
  <td>the Bird</td>
  <td>@twitter</td>
</tr>
</tbody>
</table>

Мое требование:

  • Когда я нажимаю на любую строку таблицы (либо в тексте, либо даже в промежутке между двумя столбцами) он должен перенаправить на другую Html страницу.

как я могу это сделать?

Ответы [ 5 ]

0 голосов
/ 18 февраля 2020

Сначала я предлагаю добавить класс к тегу <tr> (поэтому, если вы планируете иметь несколько таблиц на странице, это не повлияет на другую таблицу)

Затем я предполагаю, что вы используете jquery, и вы есть динамические c строки таблицы.

#.link is the class <tr class="link" data-href="https://google.com">...</tr>
#:not(a) => added this so you can add other link `<a>` to your row (remove it if not needed...)

// same page redirect
$(document).on('click', 'tr.link:not(a)', function(e){
  e.stopPropagation(); // only add this if you have <a> tag in row
  window.location.href = $(this).data('href'); // dynamic link
});

// new tab redirect
$(document).on('click', 'tr.link', function(){
  $('<a href="'+ $(this).attr('data-href') +'" target="_blank">External Link</a>')[0].click();
});
0 голосов
/ 18 февраля 2020

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

Добавьте событие щелчка по всем строкам в теле таблицы и выполните свою задачу.

$(function() {
  $('tbody tr').click(function() {
    window.location.href = 'https://www.google.com';
  })
})

)

0 голосов
/ 18 февраля 2020

попробуйте этот код

<!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
    <table class="table table-striped" id="tableId">
     <thead>
        <tr>
         <th scope="col">#</th>
         <th scope="col">First</th>
         <th scope="col">Last</th>
         <th scope="col">Handle</th>
       </tr>
     </thead>
     <tbody>
      <tr>
        <th scope="row">1</th>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
     </tr>
     <tr>
       <th scope="row">2</th>
       <td>Jacob</td>
       <td>Thornton</td>
       <td>@fat</td>
    </tr>
    <tr>
      <th scope="row">3</th>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
    </tr>
    </tbody>
    </table>

    <script>
        function addRowHandlers() {
            var table = document.getElementById("tableId");
            var rows = table.getElementsByTagName("tr");
            for (i = 0; i < rows.length; i++) {
                var currentRow = table.rows[i];
                var createClickHandler = 
                    function(row) 
                    {
                        return function() { 
                                                var cell = row.getElementsByTagName("td")[0];
                                                var id = cell.innerHTML;
                                                alert("id:" + id);
                                                window.location.href = "http://www.w3schools.com";
                                         };
                    };

                currentRow.onclick = createClickHandler(currentRow);
            }
        }
        window.onload = addRowHandlers();
    </script>
    </body>
    </html>
0 голосов
/ 18 февраля 2020

Этого также можно добиться, используя Javascript для tr (inline):

<tr onclick="document.location = 'links.html';">

Таким образом, вы можете установить разные ссылки для разных строк. Пожалуйста, проверьте ниже обновленный HTML фрагмент:

<table class="table table-striped">
 <thead>
    <tr>
     <th scope="col">#</th>
     <th scope="col">First</th>
     <th scope="col">Last</th>
     <th scope="col">Handle</th>
   </tr>
 </thead>
 <tbody>
  <tr onclick="document.location = 'http://www.google.com';">
    <th scope="row">1</th>
    <td>Mark</td>
    <td>Otto</td>
    <td>@mdo</td>
 </tr>
 <tr onclick="document.location = 'http://www.himanshu.com';">
   <th scope="row">2</th>
   <td>Jacob</td>
   <td>Thornton</td>
   <td>@fat</td>
</tr>
<tr onclick="document.location = '/links.html';">
  <th scope="row">3</th>
  <td>Larry</td>
  <td>the Bird</td>
  <td>@twitter</td>
</tr>
</tbody>
</table>
0 голосов
/ 18 февраля 2020

Это можно сделать с помощью jQuery. Привязать прослушиватель событий к нажатию кнопки TR и затем перенаправить пользователя по мере необходимости.

Ваш HTML

<table class="table table-striped">
 <thead>
    <tr>
     <th scope="col">#</th>
     <th scope="col">First</th>
     <th scope="col">Last</th>
     <th scope="col">Handle</th>
   </tr>
 </thead>
 <tbody>
  <tr>
    <th scope="row">1</th>
    <td>Mark</td>
    <td>Otto</td>
    <td>@mdo</td>
 </tr>
 <tr>
   <th scope="row">2</th>
   <td>Jacob</td>
   <td>Thornton</td>
   <td>@fat</td>
</tr>
<tr>
  <th scope="row">3</th>
  <td>Larry</td>
  <td>the Bird</td>
  <td>@twitter</td>
</tr>
</tbody>
</table>

jQuery Код

$(function() {
  $('tr').on('click', function() {
    document.location.href = 'https://google.com';

  });
});

Обычный JavaScript

var table = document.getElementById('js-table');
for(var i = 0; i < table.rows.length; i++) {
  table.rows[i].addEventListener('click', function() {
    document.location.href = "https://google.com"
  });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...