我使用Bootstrap和以下不工作:
<tbody>
<a href="#">
<tr>
<td>Blah Blah</td>
<td>1234567</td>
<td>£158,000</td>
</tr>
</a>
</tbody>
我使用Bootstrap和以下不工作:
<tbody>
<a href="#">
<tr>
<td>Blah Blah</td>
<td>1234567</td>
<td>£158,000</td>
</tr>
</a>
</tbody>
当前回答
<tbody>
<tr data-href='www.bbc.co.uk'>
<td>Blah Blah</td>
<td>1234567</td>
<td>£158,000</td>
</tr>
<tr data-href='www.google.com'>
<td>Blah Blah</td>
<td>1234567</td>
<td>£158,000</td>
</tr>
</tbody>
<script>
jQuery(document).ready(function ($) {
$('[data-href]').click(function () {
window.location = $(this).data("href");
});
});
</script>
虽然这里的主要解决方案很棒,但我的解决方案消除了对类的需求。您所需要做的就是添加包含URL的data-href属性。
其他回答
你可以在tr中使用onclick javascript方法,使其可点击,如果你需要建立你的链接,由于一些细节,你可以在javascript中声明一个函数,并在onclick中调用它,传递一些值。
另一种选择使用<a>, CSS位置和一些jQuery或JS:
HTML:
<table>
<tr>
<td>
<span>1</span>
<a href="#" class="rowLink"></a>
</td>
<td><span>2</span></td>
</tr>
</table>
CSS:
table tr td:first-child {
position: relative;
}
a.rowLink {
position: absolute;
top: 0; left: 0;
height: 30px;
}
a.rowLink:hover {
background-color: #0679a6;
opacity: 0.1;
}
然后你需要给一个宽度,使用例如jQuery:
$(function () {
var $table = $('table');
$links = $table.find('a.rowLink');
$(window).resize(function () {
$links.width($table.width());
});
$(window).trigger('resize');
});
前面没有提到的一个解决方案是在一个单元格中使用单个链接,并使用一些CSS来扩展这个链接:
table { border: 1px solid; width: 400px; overflow: hidden; } tr:hover { background: gray; } tr td { border: 1px solid; } tr td:first-child { position:relative; } a:before { content: ''; position:absolute; left: 0; top: 0; bottom: 0; display: block; width: 400px; } <table> <tr> <td><a href="https://google.com">First column</a></td> <td>Second column</td> <td>Third column</td> </tr> <tr> <td><a href="https://stackoverflow.com">First column</a></td> <td>Second column</td> <td>Third column</td> </tr> </table>
2023年的答案: 你可以在行中添加addEventListener:
var rows = document.getElementsByTagName('table')[0].rows; Array.from(rows).forEach(row => { row.addEventListener("click", function() { console.log(this.getAttribute('data-href')); // window.location.href = this.getAttribute('data-href'); }); }); body { display: flex; justify-content: center; margin-top: 20px; color: #37559d; } a { color: #5165ff; } table { border-collapse: collapse; } tr:hover { background: #f2f3ff; outline: none; cursor: pointer; } td { border: 2px solid #ccd2ff; position: relative; padding: 18px; } <table> <tbody> <tr data-href="https://www.google.com"> <td>One</td> <td>Two</td> <td>Three</td> <td>Four</td> <td> <a href="#link1">Link</a> </td> </tr> <tr data-href="https://www.amazon.com"> <td>One</td> <td>Two</td> <td>Three</td> <td>Four</td> <td> <a href="#link2">Link</a> </td> </tr> <tr data-href="https://www.stackoverflow.com"> <td>One</td> <td>Two</td> <td>Three</td> <td>Four</td> <td> <a href="#link3">Link</a> </td> </tr> </tbody> </table>
<table>
<tr tabindex="0" onmousedown="window.location='#';">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
将#替换为url, tabindex="0"使任何元素都可聚焦