如何使表格中的整行可作为链接点击? [英] how to make a whole row in a table clickable as a link?

查看:22
本文介绍了如何使表格中的整行可作为链接点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Bootstrap,但以下方法不起作用:

I'm using Bootstrap and the following doesn't work:

<tbody>
    <a href="#">
        <tr>
            <td>Blah Blah</td>
            <td>1234567</td>
            <td>£158,000</td>
        </tr>
    </a>
</tbody>

推荐答案

作者注一:

请查看下面的其他答案,尤其是那些不使用 jquery 的答案.

Author's note I:

Please look at other answers below, especially ones that do not use jquery.

为后人保留,但肯定是 2020 年错误的方法.(即使在 2017 年也不是惯用的)

Preserved for posterity but surely the wrong approach in 2020. (Was non idiomatic even back in 2017)

您正在使用 Bootstrap,这意味着您正在使用 jQuery :^),因此一种方法是:

You are using Bootstrap which means you are using jQuery :^), so one way to do it is:

<tbody>
    <tr class='clickable-row' data-href='url://'>
        <td>Blah Blah</td> <td>1234567</td> <td>£158,000</td>
    </tr>
</tbody>


jQuery(document).ready(function($) {
    $(".clickable-row").click(function() {
        window.location = $(this).data("href");
    });
});

当然你不必使用href或切换位置,你可以在点击处理函数中做任何你喜欢的事情.阅读 jQuery 以及如何编写处理程序;

Of course you don't have to use href or switch locations, you can do whatever you like in the click handler function. Read up on jQuery and how to write handlers;

使用 class 而不是 id 的优点是您可以将解决方案应用于多行:

Advantage of using a class over id is that you can apply the solution to multiple rows:

<tbody>
    <tr class='clickable-row' data-href='url://link-for-first-row/'>
        <td>Blah Blah</td> <td>1234567</td> <td>£158,000</td>
    </tr>
    <tr class='clickable-row' data-href='url://some-other-link/'>
        <td>More money</td> <td>1234567</td> <td>£800,000</td>
    </tr>
</tbody>

并且您的代码库不会改变.相同的处理程序将处理所有行.

and your code base doesn't change. The same handler would take care of all the rows.

您可以像这样使用 Bootstrap jQuery 回调(在 document.ready 回调中):

You can use Bootstrap jQuery callbacks like this (in a document.ready callback):

$("#container").on('click-row.bs.table', function (e, row, $element) {
    window.location = $element.data('href');
});

这样做的好处是不会在表格排序时重置(其他选项会发生这种情况).

This has the advantage of not being reset upon table sorting (which happens with the other option).

自从发布后 window.document.location 已过时(或至少已弃用),请改用 window.location.

Since this was posted window.document.location is obsolete (or deprecated at the very least) use window.location instead.

这篇关于如何使表格中的整行可作为链接点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆