我使用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>
当前回答
下面的代码将使您的整个表可点击。单击本例中的链接将在警告对话框中显示该链接,而不是按照该链接进行操作。
HTML:
下面是上面例子背后的HTML:
<table id="example">
<tr>
<th> </th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
<tr>
<td><a href="apples">Edit</a></td>
<td>Apples</td>
<td>Blah blah blah blah</td>
<td>10.23</td>
</tr>
<tr>
<td><a href="bananas">Edit</a></td>
<td>Bananas</td>
<td>Blah blah blah blah</td>
<td>11.45</td>
</tr>
<tr>
<td><a href="oranges">Edit</a></td>
<td>Oranges</td>
<td>Blah blah blah blah</td>
<td>12.56</td>
</tr>
</table>
CSS
而CSS:
table#example {
border-collapse: collapse;
}
#example tr {
background-color: #eee;
border-top: 1px solid #fff;
}
#example tr:hover {
background-color: #ccc;
}
#example th {
background-color: #fff;
}
#example th, #example td {
padding: 3px 5px;
}
#example td:hover {
cursor: pointer;
}
jQuery
最后是jQuery,它使魔术发生:
$(document).ready(function() {
$('#example tr').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
});
它所做的是,当单击一行时,搜索属于锚的href。如果找到一个,则将窗口的位置设置为该href。
其他回答
我知道有人已经写了差不多一样的,但我的方式是正确的方式(div不能是A的子),也最好使用类。
您可以使用CSS模拟一个表,并将a元素作为行
<div class="table" style="width:100%;">
<a href="#" class="tr">
<span class="td">
cell 1
</span>
<span class="td">
cell 2
</span>
</a>
</div>
css:
.table{display:table;}
.tr{display:table-row;}
.td{display:table-cell;}
.tr:hover{background-color:#ccc;}
你不能这么做。它是无效的HTML。你不能把<a>放在<tbody>和<tr>之间。试试这个吧:
<tr onclick="window.location='#';">
...
</tr>
为指针视图添加样式
[data-href] { cursor: pointer; }
当您开始处理它时,您需要使用JavaScript在HTML之外分配单击处理程序。
一个更灵活的解决方案是使用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解决方案,请随意添加。
我更喜欢使用onclick=""属性,因为它很容易使用和理解的新手喜欢
<tr onclick="window.location='any-page.php'">
<td>UserName</td>
<td>Email</td>
<td>Address</td>
</tr>
这里有一个简单的解决办法。
<tr style='cursor: pointer; cursor: hand;' onclick="window.location='google.com';"></tr>