13

HTML テーブルの行をリンクにする最良の方法は何ですか? 現在、jquery を使用して行をゼブラ ストライプし、onmouseover/off で選択した行を強調表示しているため、JavaScript が答えの場合は jquery を使用してください。

4

6 に答える 6

2

テーブルを一般的な要素に置き換えても構わない場合は、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>
于 2012-08-13T10:04:14.853 に答える
2

tr 要素の onclick イベント ハンドラーを登録します。jQueryを使用すると、次のようになります。

$("tr").bind("click", function(){ 
  window.location = 'http://www.example.com/'; 
});
于 2009-02-20T12:26:00.887 に答える
1
<td>
    <a href="/whatevs/whatevs">
        <div class="tdStreacher"> linkName
        </div>
    </a>
</td>

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

このように、各セルのすべての領域がリンクとして機能するため、行全体がリンクとして機能します。

于 2011-07-18T15:00:37.720 に答える
1

Nick のソリューションに基づく 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's 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's 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 にラップされることを期待します。ニックの元のソリューションは、高さが異なる隣接セルでは機能しなかったため、高さは明示的に設定されています。a-要素を必ずブロックとしてスタイルしてください。パディングを適用する場合は、テーブル セルの代わりに a 要素に適用します。

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

電話するだけ

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

それが役に立てば幸い。乾杯、リチャード

于 2012-03-02T17:28:29.303 に答える