Want to make entire TD cell an anchor
I have a <table>
where each <td>
holds only an anchor. I'd like users to be able to click anywhere in the cell to visit that reference rather than only on the anchor text itself. I imagine there must be a bit of jQuery to do this easily. Can anyone help?
Edit: To complicate things, my td
's have some top and bottom padding. A display: block;
rule doesn't seem to work in this case. I've edited the example:
CSS:
table#mainmenu td {
padding: 9px 8px 5px;
border: none;
border-bottom: 1px solid #ccc;
border-left: 1px dotted;
text-align: left;
}
Example:
<table>
<tr>
<td><a href="foo.html">Foo</a></td>
<td><a href="bar.html">Bar</a></td>
</tr>
<tr>
<td开发者_开发百科><a href="foobar.html">FooBar</a></td>
<td><a href="barfoo.html">BarFoo</a></td>
</tr>
</table>
Just make the A tag display: block
.
table td a {
display: block;
}
http://jsfiddle.net/userdude/6VZ8t/
Or, if you insist on jQuery:
$('table td a').css('display','block');
http://jsfiddle.net/userdude/a2EAz/
EDIT
Since I wasn't able to find a CSS-only way to select a parent TD of a child A, this solution does use jQuery:
function doTablePadding() {
$td = $('table td');
$td.has('a').css('padding','0');
padding = $td.not(':has(a)').css('padding-top') + " ";
padding += $td.not(':has(a)').css('padding-right') + " ";
padding += $td.not(':has(a)').css('padding-bottom') + " ";
padding += $td.not(':has(a)').css('padding-left') + " ";
$td.children('a').css('padding',padding);
}
doTablePadding();
$('table tbody').append("<tr><td>Stuff</td><td><p>Other stuff</p></td></tr>");
$('table tbody').append('<tr><td><a href="foo.html">Foo</a></td><td><a href="bar.html">Bar</a></td></tr>');
doTablePadding();
http://jsfiddle.net/userdude/Mekjg/1
Note that this is running from $(document).ready();
.
EDIT 2
As mu is too short notes, negative margins should work (and no jQuery):
td {
padding: 5px;
background: #0ff;
border: 1px solid black;
}
td a {
display: block;
margin: -5px;
padding: 5px;
background: #f0f;
}
http://jsfiddle.net/ambiguous/seqpp/
$(function(){
$('td').click(function(){
window.location = $("a", this).attr("href");
});
})
Demo: http://jsfiddle.net/rarTf/
just make the css as
table td { cursor: pointer; }
and make script as
$('table td').click(function(){ window.location.href=$('a',this).attr('href'); });
精彩评论