jQuery:除了一列之外,使整个表行成为一个链接
我有一个脚本,可以使每个表行可单击(作为链接),但我需要保持最后一列不作为此列作为“编辑”按钮。 任何人都可以帮我修改脚本,这样它会起作用吗?
到目前为止jQuery:
$(document).ready(function() { $('#movies tr').click(function() { var href = $(this).find("a").attr("href"); if(href) { window.location = href; } }); });
这是一行的HTML:
1 Tintin Tintin and Captain Haddock set off on a treasure hunt for a sunken ship. edit .....
你需要更深入一步并控制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 element var href = $(this).closest("tr").find("a").attr("href"); if(href) { window.location = href; } }); }); });
或者,您可以在最后一个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; } });
试试这个
$(document).ready(function() { $('#movies tr:not('.odd')').click(function() { var href = $(this).find("a").attr("href"); if(href) { window.location = href; } }); });
我建议用某个类或者simliar将
的paddinng改为0,然后让
标签display: block
以便浏览器只需点击整个
-tag
。
这里的优点是您的浏览器可以更好地处理链接,例如,如果需要,可以在新窗口中打开链接。
它可能不适合您的解决方案,但值得考虑类似的情况。
$('tr').each(function () { $(this).children('td:not(:first)').click(function () { window.location = $(this).closest('tr').data('href'); return false; }); });
让我发布另一个例子,通过单击除特定列之外的任何列来选择/取消选择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]); });