使用 jQuery 使表格行 (tr) 可点击(使用 href 链接,然后悬停!?)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2375904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:21:50  来源:igfitidea点击:

Making a table row (tr) clickable with jQuery (with an a href link, and hover!?)

jqueryhyperlinkhtml-tableclick

提问by Nick

Just a (hopefully) quick question, I have the following HTML code:

只是一个(希望如此)快速问题,我有以下 HTML 代码:

<tr>
 <td><img src="img/icons/file_pdf.png"></td>
 <td><a href="../upload/1267473577.pdf">Bulletin 1st March 2010</a></td>
 <td>(01/03/10)</td>
</tr>

Ideally I'd like a way to grab the a href link using jQuery and make it so that no matter where you click on that particular table row, it will take you to that link.

理想情况下,我想要一种使用 jQuery 获取 href 链接的方法,并使其无论您在何处单击该特定表格行,它都会将您带到该链接。

Is there any way to do this? I can do it via icky inline JavaScript as an absolute last resort, but since finding out about jQuery I quite like the idea of being able to do this cleanly and unobtrusively :-)

有没有办法做到这一点?我可以通过 icky 内联 JavaScript 作为绝对的最后手段来做到这一点,但是自从发现了 jQuery,我非常喜欢能够干净利落地做到这一点的想法:-)

回答by cletus

Assuming it's a "normal" link (not a Javascript trigger) this will be sufficient:

假设它是一个“正常”链接(不是 Javascript 触发器),这就足够了:

$("tr").click(function() {
  window.location.href = $(this).find("a").attr("href");
});

You will probably want to communicate this behaviour to the user in some way. The minimal approach would be changing the cursor while hovering over the row.

您可能希望以某种方式将这种行为传达给用户。最小的方法是在悬停在行上时更改光标。

回答by Scott Yu - builds stuff

I found this solution to work well for me.

我发现这个解决方案对我很有效。

$('table tr').live("click",function(e){ 
    if (e.target instanceof HTMLInputElement || e.target instanceof HTMLAnchorElement){
        return;
        }
        alert('works');
});

回答by leaber

If you have another link inside the table, like a delete link, you may want to use the event object to check if the user clicked over that particular link and avoid the redirection.

如果表中有另一个链接,例如删除链接,您可能需要使用事件对象来检查用户是否点击了该特定链接并避免重定向。

Example HTML:

示例 HTML:

<tr title="http://path/to/download">
  <td><img src="img/icons/file_pdf.png"></td>
  <td><a href="/path/to/delete">Delete</a></td>
  <td>(01/03/10)</td>
</tr>

Example JavaScript:

示例 JavaScript:

$("tr").click(function(event) {
  if(event.target.nodeName != "A"){
    window.location.href = $(this).attr("title");
  }
});

Usually my tables have an action cell with edit and delete, so I use the row click event to redirect to the show action.

通常我的表格有一个带有编辑和删除的操作单元格,所以我使用行单击事件重定向到显示操作。