如何向表行<tr>添加超链接

Raj*_*kar 13 javascript css php html-table

我有一个表,其表行在<tr>循环中生成,以形成多行.

我想给<a>每个人单独的链接<tr>.由于在表中我们只能添加添加数据<td>,我无法实现.

有没有其他方法来实现这一目标?专家请帮忙.

ahm*_*106 29

HTML:

<table>
    <tr href="http://myspace.com">
      <td>MySpace</td>
    </tr>
    <tr href="http://apple.com">
      <td>Apple</td>
    </tr>
    <tr href="http://google.com">
      <td>Google</td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

使用jQuery库的JavaScript :

$(document).ready(function(){
    $('table tr').click(function(){
        window.location = $(this).attr('href');
        return false;
    });
});
Run Code Online (Sandbox Code Playgroud)

你可以在这里试试:http://jsbin.com/ikada3

CSS(可选):

table tr {
    cursor: pointer;
}
Run Code Online (Sandbox Code Playgroud)

或者HTML有效版本data-href代替href:

<table>
    <tr data-href="http://myspace.com">
      <td>MySpace</td>
    </tr>
    <tr data-href="http://apple.com">
      <td>Apple</td>
    </tr>
    <tr data-href="http://google.com">
      <td>Google</td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

JS:

$(document).ready(function(){
    $('table tr').click(function(){
        window.location = $(this).data('href');
        return false;
    });
});
Run Code Online (Sandbox Code Playgroud)

CSS:

table tr[data-href] {
    cursor: pointer;
}
Run Code Online (Sandbox Code Playgroud)

  • 使用`data-href`可以解决无效属性的问题. (5认同)
  • 另一个问题是你打破了中间点击. (4认同)

Mic*_*ins 10

玩@ ahmet2016并保持W3C标准.

HTML:

<tr data-href='LINK GOES HERE'>
    <td>HappyDays.com</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

CSS:

*[data-href] {
    cursor: pointer;
}
Run Code Online (Sandbox Code Playgroud)

jQuery的:

$(function(){       
    $('*[data-href]').click(function(){
        window.location = $(this).data('href');
        return false;
    });
});
Run Code Online (Sandbox Code Playgroud)


小智 8

我发现将表格行转换为链接的最简单方法是使用带有window.location的onclick属性.

<table>
<tr onclick="window.location='/just/a/link.html'">
<td></td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)