ハルの読書と勉強録

読書の記録や勉強の覚書です。

【jQuery】HTMLのtableの行にリンクを設定する

jQueryを使用して、tableの行をクリックできるようにして、リンクを設定する方法です。

実装手順

※前提:jQueryが使用できる状態(Bootstrapでも可)

  1. 対象のtrタグに実装用のclassを付与(jQueryでの付与でも可)
  2. trタグにカスタム属性(data-〇〇)を付与し、リンク先を設定
  3. jQueryでクリック時にカスタム属性のリンク先へ遷移するよう記述

対象HTML

品名 ストック 開封
洗剤 1 2019/10/12
<table border=1>
    <thead>
        <th>品名</th>
        <th>ストック</th>
        <th>開封日</th>
    </thead>
    <tbody>
        <tr>
            <td>洗剤</td>
            <td>1</td>
            <td>2019/10/12</td>
        </tr>
    </tbody>
</table>

実装作業

1.対象のtrタグに実装用のclassを付与

<table border=1>
    <thead>
        <th>品名</th>
        <th>ストック</th>
        <th>開封日</th>
    </thead>
    <tbody>
        <!-- 実装用classを付与 -->
        <tr class="clickable-row">
            <td>洗剤</td>
            <td>1</td>
            <td>2019/10/12</td>
        </tr>
     </tbody>
</table>

2.trタグへのカスタム属性の付与とリンク先設定

ここではカスタム属性を「data-href」とします。

<table border="1">
    <thead>
        <th>品名</th>
        <th>ストック</th>
        <th>開封日</th>
    </thead>
    <tbody>
    <!-- カスタム属性(data-href)にリンク先を指定 -->
        <tr class="clickable-row" data-href="https://ja.wikipedia.org/wiki/%E6%B4%97%E5%89%A4">
            <td>洗剤</td>
            <td>1</td>
            <td>2019/10/12</td>
        </tr>
    </tbody>
</table>

3.jQueryでクリック時の挙動を記述

//jQuery.js(もしくは実装対象HTMLのscriptタグ内に記述)
$(function($) {
    $(".clickable-row").css("cursor","pointer").click(function() {
        location.href = $(this).data("href");
    });
});

↓解説コメント付き

//jQuery.js(もしくは対象HTMLの<script>タグ内に記述)
$(function($) {
 //clickable-rowクラスの行をマウスオーバーするとカーソルをポインターに変更
    $(".clickable-row").css("cursor","pointer").click(function() {
 //クリックで「data-href」のリンク先へ遷移
        window.href = $(this).data("href");
    });
});

実装完了サンプル

品名 ストック 開封
洗剤 1 2019/10/12

参考

MDN公式 Window.location