7

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

使用下面的代码,可点击的行仅对整行有效,除了我需要的最后一个单元格,因为我在此单元格中有管理链接(激活、编辑、删除等行的链接)。唯一的问题是,无论您单击哪一行,都会将您转到最上面一行的链接。我认为这与我的选择器有关,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');
    }
);
4

3 回答 3

11

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

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

这意味着它将获取单击的元素 $(this) 作为 jquery 对象,然后转到其父级。(行元素)。

于 2011-09-23T06:36:44.100 回答
1
$('#dataTable tr td:not(:last-child)').click(function ()    {
 location.href = $(this).parent().find('td a').attr('href'); 
});  

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

于 2011-09-23T06:37:32.197 回答
0

替代答案。

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");
  });
});
于 2020-03-17T06:56:09.883 回答