5

我有一个脚本可以使每个表格行可点击(作为链接),但是我需要最后一列保持不变,因为该列作为“编辑”按钮。任何人都可以帮我修改脚本以使其正常工作吗?

到目前为止的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>
  .....
4

6 回答 6

11

您需要更深入地控制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;
         }              
      });
   });
});
于 2011-11-05T11:17:16.720 回答
3

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

$('#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;
    }
});
于 2011-11-05T12:46:56.943 回答
0

试试这个

$(document).ready(function() {
  $('#movies tr:not('.odd')').click(function() {
    var href = $(this).find("a").attr("href");
    if(href) {
      window.location = href;
    }
  });
});
于 2011-11-05T11:26:25.637 回答
0

我建议将<td>s paddinng 设置为 0 与某个类或类似,并将<a>标签放在里面display: block,以便浏览器只需单击<a>整个<td>.

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

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

于 2011-11-05T12:28:01.667 回答
0
$('tr').each(function () {
    $(this).children('td:not(:first)').click(function () {
        window.location = $(this).closest('tr').data('href');
        return false;
    });
});
于 2014-02-03T23:11:53.703 回答
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]);
});
于 2015-01-04T07:00:16.143 回答