【问题标题】:How to make the entire row in a table clickable as a link, except the last column?如何使表格中的整行可作为链接点击,除了最后一列?
【发布时间】:2011-09-23 06:30:59
【问题描述】:

我设法让我的表中的行可以点击并链接到<a> 元素的href 属性。但是,当我让选择器只选择除最后一列之外的行时,我开始遇到问题。

使用下面的代码,可点击的行仅对整行有效,除了我需要的最后一个单元格,因为我在此单元格中有管理链接(激活、编辑、删除等行的链接)。唯一的问题是,无论您单击哪一行,都会将您转到最顶行的链接。我认为这与我的 find('td a') 选择器有关,但我无法弄清楚。

$('#dataTable tr td:not(:last-child)').click(function () {
    location.href = $('#dataTable tr').find('td a').attr('href');
});  

悬停效果很好,只有当鼠标悬停在除最后一列之外的任何单元格上时才会更改指针。

$('#dataTable tr td:not(:last-child)').hover(
    function() { 
        $(this).css('cursor','pointer');
    },
    function() {
        $(this).css('cursor','auto');
    }
);

【问题讨论】:

    标签: jquery rows clickable


    【解决方案1】:

    这是因为你得到了表中的所有 tr,然后将返回找到的第一个锚点,尝试像这样更改它:

    $('#dataTable tr td:not(:last-child)').click(function ()    {
     location.href = $(this).parent().find('td a').attr('href');
    });
    

    这意味着它将被点击的元素 $(this) 作为一个 jquery 对象,然后转到它的父级。 (行元素)。

    【讨论】:

    • 非常感谢。我一直试图让这个工作整夜。我是 jquery 的新手,我想我正在抓住所有的 tr,我只是不知道如何改变它。再次感谢!
    【解决方案2】:
    $('#dataTable tr td:not(:last-child)').click(function ()    {
     location.href = $(this).parent().find('td a').attr('href'); 
    });  
    

    我认为这应该可行。您的代码始终从它在数据表中找到的第一个“td a”中获取 href。此代码采用它在您正在寻找的特定 td 中找到的 a。

    【讨论】:

      【解决方案3】:

      另一种答案。

      HTML:

      <table>
        <tbody>
          <tr data-href="#">
            <td>first</td>
            <td>second</td>
            <td>
              <div class="dropdown">...</div>
            </td>
          </tr>
        </tbody>
      </table>
      

      JS:

      jQuery(document).ready(function ($) {
        $("tbody").on('click', 'tr td:not(:last-child)', function () {
          window.location = $(this).parent().data("href");
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-13
        • 1970-01-01
        • 2012-07-18
        • 2020-11-23
        相关资源
        最近更新 更多