如何将HTML表格中的一行设置为链接?我目前使用jQuery来实现斑马线条纹和鼠标悬停/选中行高亮显示,所以如果需要JavaScript,请使用jQuery。
如何将HTML表格中的一行设置为链接?我目前使用jQuery来实现斑马线条纹和鼠标悬停/选中行高亮显示,所以如果需要JavaScript,请使用jQuery。
我只使用CSS:
<style>
table.collection {width:500px;border-collapse:collapse;}
table.collection tr {background-color:#fff; border-bottom: 1px #99b solid;}
table.collection tr:hover {background-color:#ffe;}
table.collection td {display:table-cell;border-bottom: 1px #99b solid; padding:0px;}
table.collection td a {text-decoration:none; display:block; padding:0px; height:100%;}
</style>
<table class="collection">
<tr>
<td><a href="#">Linky1</a></td>
<td><a href="#">Data1</a></td>
</tr>
<tr>
<td><a href="#">Linky2</a></td>
<td><a href="#">Data2</a></td>
</tr>
</table>
$(document).ready(function(){
$("tr").click(function(){
/* personally I would throw a url attribute (<tr url="http://www.hunterconcepts.com">) on the tr and pull it off on click */
window.location = $(this).attr("url");
});
});
a
元素相同的方式单击tr
时(即使用shift +单击或cmd +单击以打开新标签等)。 - hohner<style>
.table {
border-collapse: collapse;
border-spacing: 0;
display: table;
}
.tr {
display: table-row;
}
.td {
display: table-cell;
}
</style>
<section class="table">
<a class="tr" href="#">
<div class="td">
A
</div>
<div class="td">
B
</div>
<div class="td">
C
</div>
</a>
</section>
为 tr 元素注册 onclick 事件处理程序。使用 jQuery 可以像这样:
$("tr").bind("click", function(){
window.location = 'http://www.example.com/';
});
这是一个基于Nick的解决方案的jQuery插件。
(function($) {
$.fn.linkWholeRows = function() {
// for each object
return this.each(function() {
// for each row
$(this).find('tbody tr').each(function() {
// get the first link's href
var href = $(this).find('td > a').attr('href');
// if none found then
if (href === undefined) {
return true; // continue
}
// wrap all cells with links that do not already have a link
$(this).children().not(':has(a)').each(function() {
$(this).contents().wrapAll('<a href="' + href + '" />');
});
// apply the row's height to all links
// in case that the cells' content have different heights
var height = $(this).children().css('height');
$(this).find('td > a').each(function() {
$(this).css('height', height);
// do not forget to apply display:block to the links
// via css to make it work properly
});
}); // each row
}); // each object
};
})(jQuery);
期望行被包裹在tbody中。高度被明确设置,因为Nick的原始解决方案对于具有不同高度的相邻单元格对我来说无效。 确保将a元素样式设置为块级元素。如果要应用填充,请将其应用于a元素而不是表格单元格:
a {
display: block;
padding: 0.25em 0.5em;
}
tbody td { padding: 0; }
$('#your-table').linkWholeRows();
<td>
<a href="/whatevs/whatevs">
<div class="tdStreacher"> linkName
</div>
</a>
</td>
.tdStreacher{
height: 100%;
width: 100%;
padding: 3px;
}
这样,每个单元格的整个区域都将作为一个链接,因此整行都将作为一个链接。