使表行可单击
我有一个在hover时具有背景颜色的表格行。 当用户在背景颜色区域内单击时,它应该抓住行内锚标记的链接并将用户带到那里..我该怎么做?
Go Here To find about all the interestng animals found in this tourist attractions including zebra, giraffe..... ....
如何获取锚标签href值?
$('tr #ClickableRow').click(function () { window.location.href=Anchor tag's href value });
好吧首先,如果您仍然使用id,则无需在选择器中指定tr。 如果你想要,你应该在没有空格的情况下一起编写,因为tr得到了那个id。
其次,你需要使用this
和find()
来选择被点击的表格行中的第一个链接并获得它的href
属性:
$('tr#ClickableRow').click(function () { var url = $(this).find('a:first').attr('href'); window.location.href = url; });
以下也有效:
location = $(this).find('a:first').attr( 'href' );
请参阅: Javascript:设置location.href与位置
在你的情况下
$('#ClickableRow').click(function () { window.location = $("#ClickableRow a:first").attr('href'); });
你可以在http://jsfiddle.net/上测试。
要使其看起来像可点击,您可以添加此项
JavaScript的:
$('#ClickableRow').hover( function () { if ($(this).find("th").length > 0) return; $(this).addClass("gridRowHover"); }, function () { $(this).removeClass("gridRowHover"); } );
CSS
.gridRowHover{ cursor: pointer; }
通用函数 ,使任何表行可单击
function bindRowClick(itemId, eventHandler) { var binder = "tr"; $("#" + itemId).find(binder).click(eventHandler); }
ItemId
将是您的表id, eventHandler
是要执行的函数。
怎么样:
$('#ClickableRow').click(function () { window.location = $('a:first', this).attr('href'); });
你还需要删除tr
和#ClickableRow
之间的空格,否则它将作为子元素。
$('tr#ClickableRow').click(function () { window.location = $(this).find('a').attr("href"); });