我使用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>
当前回答
一个更灵活的解决方案是使用data-href属性来定位任何对象。这样你就可以在不同的地方轻松地重用代码。
<tbody>
<tr data-href="https://google.com">
<td>Col 1</td>
<td>Col 2</td>
</tr>
</tbody>
然后在你的jQuery中,只需瞄准具有该属性的任何元素:
jQuery(document).ready(function($) {
$('*[data-href]').on('click', function() {
window.location = $(this).data("href");
});
});
不要忘记样式你的css:
[data-href] {
cursor: pointer;
}
现在,您可以将data-href属性添加到任何元素,它都可以工作。当我写这样的片段时,我希望它们是灵活的。如果你有一个香草的js解决方案,请随意添加。
其他回答
另一种选择使用<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');
});
你可以给行一个id,例如。
<tr id=“special”> ... </tr>
然后使用jquery说:
$(' #特别').onclick(函数(){窗口= " http://urltolinkto.com/x/y/z ";})
我更喜欢使用onclick=""属性,因为它很容易使用和理解的新手喜欢
<tr onclick="window.location='any-page.php'">
<td>UserName</td>
<td>Email</td>
<td>Address</td>
</tr>
您可以将按钮角色添加到表行中,Bootstrap将在不更改css的情况下更改游标。我决定使用这个角色作为一种方法,用很少的代码轻松地使任何行都可以单击。
Html
<table class="table table-striped table-hover">
<tbody>
<tr role="button" data-href="#">
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
</tr>
</tbody>
</table>
jQuery
$(function(){
$(".table").on("click", "tr[role=\"button\"]", function (e) {
window.location = $(this).data("href");
});
});
您可以应用相同的原则将按钮角色添加到任何标记。
你可以在每个<td>中包含一个锚,如下所示:
<tr>
<td><a href="#">Blah Blah</a></td>
<td><a href="#">1234567</a></td>
<td><a href="#">more text</a></td>
</tr>
然后你可以使用display:block;使整行可单击。
tr:hover {
background: red;
}
td a {
display: block;
border: 1px solid black;
padding: 16px;
}
这里是jsFiddle的例子。
这可能是最优的,除非使用JavaScript。