jQuery:除了一列之外,使整个表行成为一个链接

问题描述 投票:4回答:6

我有一个脚本,可以使每个表行可单击(作为链接),但我需要保持最后一列不作为此列作为“编辑”按钮。任何人都可以帮我修改脚本,这样它会起作用吗?

这里jQuery到目前为止:

$(document).ready(function() {
  $('#movies tr').click(function() {
    var href = $(this).find("a").attr("href");
    if(href) {
      window.location = href;
    }
  });
});

这是一行的HTML:

<table id="movies">
  <tr class='odd'>
    <td>1</td>
    <td><a href='/film.php?id=1'></a>Tintin</td>
    <td>Tintin and Captain Haddock set off on a treasure hunt for a sunken ship.</td>
    <td><a href='/edit.php?id=1'>edit</a></td>
  </tr>
  .....
jquery html-table clickable
6个回答
10
投票

你需要更深入一步并控制tr的元素,将点击处理程序绑定到每个td,这不是tr中的最后一个:

$(document).ready(function()
{
   $('#movies tr').each(function(i,e)
   {
      $(e).children('td:not(:last)').click(function()
      {
         //here we are working on a td element, that's why we need
         //to refer to its parent (tr) in order to find the <a> element
         var href = $(this).closest("tr").find("a").attr("href");
         if(href)
         {
            window.location = href;
         }              
      });
   });
});

3
投票

或者,您可以在最后一个col按钮事件处理程序中使用event.stopImmediatePropagation()

$('#movies tr').click(function () {
    var href = $(this).find("a").attr("href");
    if(href) window.location = href;
});

$('#movies input:button').click(function (e) {
    // button's stuff
    e.stopImmediatePropagation();
});

优点(或不方便)是允许您单击最后一个单元格中的按钮。 (在边距填充中)。我可能会很不方便,因为按钮未命中点击会打开链接页面并让用户感到惊讶。

另一种选择可以是只使用一个事件处理程序,它决定使用event.which执行的操作。这是我最喜欢的方法,因为它限制了事件处理程序的数量。委托的使用也是出于同样的原因。一个按表处理,而不是一个一个。

$('#movies').delegate('tr', 'click', function (e) {
    if ( $(e.target).is('input:button') )  {
        // button's stuff
    }
    else {
        var href = $(this).find("a").attr("href");
        if(href) window.location = href;
    }
});

0
投票

试试这个

$(document).ready(function() {
  $('#movies tr:not('.odd')').click(function() {
    var href = $(this).find("a").attr("href");
    if(href) {
      window.location = href;
    }
  });
});

0
投票

我建议将<td>s paddinng改为0,使用某个类或simliar,并将<a>标签内置为display: block,以便浏览器只需点击整个<a>上的<td>-tag。

这里的优点是您的浏览器可以更好地处理链接,例如,如果需要,可以在新窗口中打开链接。

它可能不适合您的解决方案,但值得考虑类似的情况。


0
投票
$('tr').each(function () {
    $(this).children('td:not(:first)').click(function () {
        window.location = $(this).closest('tr').data('href');
        return false;
    });
});

0
投票

让我发布另一个例子,通过单击除特定列之外的任何列来选择/取消选择DataTables中的行。

$('#my_table_id tbody').on( 'click', 'td:not(.prohibited_td_class)', function() {
      $(this).closest("tr").toggleClass('selected');
      // If you are also using DataTables, see which rows you've selected.
      alert(""+table.rows('.selected').toJQuery()[0]);
});
© www.soinside.com 2019 - 2024. All rights reserved.