テーブルの行ごとリンクをクリック出来るようにする
Result
jQuery
jQuery(function($) {
//data-hrefの属性を持つtrを選択しclassにclickableを付加
$('tr[data-href]').addClass('clickable')
//クリックイベント
.click(function(e) {
//e.targetはクリックした要素自体、それがa要素以外であれば
if(!$(e.target).is('a')){
//その要素の先祖要素で一番近いtrの
//data-href属性の値に書かれているURLに遷移する
window.location = $(e.target).closest('tr').data('href');}
});
});
css
td, th {
padding: 5px 10px;
}
thead th {
background: #110303;
color: #fff;
}
tbody tr {
border-bottom: 1px dotted #D8D5D5;
}
tbody td {
border: 1px dotted #D8D5D5;
border-width: 0px 1px;
-webkit-transition: background-color .1s linear;
-moz-transition: background-color .1s linear;
transition: background-color .1s linear;
}
tbody tr:first-child {
border-top: none;
}
tbody tr.even td {
background: #fbfbfb;
}
tbody tr.clickable:hover td {
background: #ecf2fa;
cursor: pointer;
}
html
<table>
<thead>
<tr>
<th>地名</th>
<th>読み方</th>
<th>En</th>
<th>詳細</th>
<th>その他</th>
</tr>
</thead>
<tbody>
<tr data-href="http://ja.wikipedia.org/wiki/%E6%9D%B1%E4%BA%AC">
<td>東京</td>
<td>とうきょう</td>
<td>Tokyo</td>
<td>日本の事実上の首都がある</td>
<td><a href="#">ダミーリンク</a></td>
</tr>
<tr class="even" data-href="http://ja.wikipedia.org/wiki/%E4%BA%AC%E9%83%BD">
<td>京都</td>
<td>きょうと</td>
<td>Kyoto</td>
<td>794年に日本の首都に定められた</td>
<td><a href="#">ダミーリンク</a></td>
</tr>
<tr data-href="http://ja.wikipedia.org/wiki/%E9%9D%99%E5%B2%A1%E7%9C%8C">
<td>静岡</td>
<td>しずおか</td>
<td>Shizuoka</td>
<td>静岡市と浜松市の2つの政令指定都市を有する</td>
<td><a href="#">ダミーリンク</a></td>
</tr>
<tr class="even" data-href="http://ja.wikipedia.org/wiki/%E5%A4%A7%E9%98%AA">
<td>大阪</td>
<td>おおさか</td>
<td>Osaka</td>
<td>関西地区の経済・文化の中心地</td>
<td><a href="#">ダミーリンク</a></td>
</tr>
</tbody>
</table>
via
THE HAM MEDIA BLOG