Подтвердить что ты не робот

Ссылка на строку HTML-таблицы

Каков наилучший способ сделать строку таблицы HTML ссылкой? В настоящее время я использую jquery для полосы zebra для строк, а также для выделения выделенной строки onmouseover/off, поэтому, если JavaScript является ответом, используйте jquery.

4b9b3361

Ответ 1

Я просто использую css:

<style>
table.collection {width:500px;border-collapse:collapse;}
table.collection tr {background-color:#fff; border-bottom: 1px #99b solid;}
table.collection tr:hover {background-color:#ffe;}
table.collection td {display:table-cell;border-bottom: 1px #99b solid; padding:0px;}
table.collection td a {text-decoration:none; display:block; padding:0px; height:100%;}
</style>
<table class="collection">
<tr>
    <td><a href="#">Linky1</a></td>
    <td><a href="#">Data1</a></td>
</tr>
<tr>
    <td><a href="#">Linky2</a></td>
    <td><a href="#">Data2</a></td>
</tr>
</table>

Ответ 2

$(document).ready(function(){
   $("tr").click(function(){
      /* personally I would throw a url attribute (<tr url="http://www.hunterconcepts.com">) on the tr and pull it off on click */
      window.location = $(this).attr("url");

   });
});

Ответ 3

Зарегистрируйте обработчик события onclick для элемента tr. Что-то вроде этого с помощью jQuery:

$("tr").bind("click", function(){ 
  window.location = 'http://www.example.com/'; 
});

Ответ 4

Вам не нужен jQuery, если вы не возражаете заменить таблицу на общие элементы:

<style>
    .table {
        border-collapse: collapse;
        border-spacing: 0;
        display: table;
    }
    .tr {
        display: table-row;
    }
    .td {
        display: table-cell;
    }

</style>

<section class="table">
    <a class="tr" href="#">
        <div class="td">
            A
        </div>
        <div class="td">
            B
        </div>
        <div class="td">
            C
        </div>
    </a>
</section>

Ответ 5

<td>
    <a href="/whatevs/whatevs">
        <div class="tdStreacher"> linkName
        </div>
    </a>
</td>

.tdStreacher{
    height: 100%;
    width: 100%;
    padding: 3px;
}

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

Ответ 6

Вот плагин jQuery, основанный на решении Ника.

(function($) {
  $.fn.linkWholeRows = function() {

    // for each object
    return this.each(function() {

      // for each row
      $(this).find('tbody tr').each(function() {
        // get the first link href
        var href = $(this).find('td > a').attr('href');
        // if none found then
        if (href === undefined) {
          return true; // continue
        }

        // wrap all cells with links that do not already have a link
        $(this).children().not(':has(a)').each(function() {
          $(this).contents().wrapAll('<a href="' + href + '" />');
        });

        // apply the row height to all links
        // in case that the cells' content have different heights
        var height = $(this).children().css('height');
        $(this).find('td > a').each(function() {
          $(this).css('height', height);
          // do not forget to apply display:block to the links
          // via css to make it work properly
        });
      }); // each row

    }); // each object

  };
})(jQuery);

Ожидает, что строки будут завернуты в tbody's. Высота устанавливается явно, так как исходное решение Nick не работает для меня на соседних ячейках с разной высотой. Удостоверьтесь, что стиль a-elements является блоком. Если вы хотите применить прописку, примените ее к элементам a, а не к ячейкам таблицы:

a {
  display: block;
  padding: 0.25em 0.5em;
}
tbody td { padding: 0; }

Просто позвоните

$('#your-table').linkWholeRows();

Надеюсь, это поможет. Ура, Ричард