我有一个表格和这段代码,用于查找 href 并使整行可点击:
$(document).ready( function() {
$('table tr').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
但是,有一个问题,那就是我的右键单击没有为我提供“在新标签页中打开链接”选项 和窗口等类似普通 href 链接的东西。
使用 div 代替表格不是一种选择。
如何解决?
是否有任何 jQuery 插件可以为我修复它?
我的表看起来像这样(它更大,有更多的 td,但只是为了说明):
<table>
<tr>
<td>
<a href="http://example.com">Some link</a>
<span>Bla bla bla</span>
</td>
<td>
<span>Some text</span>
</td>
</tr>
<tr>
<td>
<a href="http://someotherlink.com">Some link</a>
<span>Other text</span>
</td>
<td>
<span>Something else</span>
</td>
</tr>
<tr>
...
</tr>
</table>
编辑:我需要像当前代码一样自动获取 href 值: $(this).find("a").attr("href");
编辑 2:我需要整个 tr 可点击(作为一个 block )。使用上述方法是可能的。但是,无法单击该行并选择“在新选项卡中打开链接”。只有当我将鼠标悬停在 a href 上时,此选项才可用。但我需要它也在整行。因此,如果用户想使用鼠标中键或右键单击并从上下文菜单中选择“在新选项卡中打开”来打开多个新选项卡,他就可以做到。现在还不可能。
最佳答案
你为什么不尝试这样的事情:
JS:
$(document).ready(function(){
$("table tr").mousedown(function(e){
document.oncontextmenu = function() {return false;};
e.preventDefault();
var href = $(this).find("a").attr("href");
if( e.button == 2 ) {
$(this).find('td:first').prepend('<div class="blank"><a href="' + href + '" target="_blank">Open in new window</a></div>').find('.blank').css('left',e.pageX + 'px').css('top',e.pageY + 'px').fadeIn(400);
} else if(e.button === 0) {
if(href) {
window.location = href;
}
}
});
$(document).on('click','.blank a',function(){
$(this).parent().fadeOut(400,function() {
$(this).remove();
});
}).on('mouseleave','.blank',function(){
$(this).fadeOut(400, function(){
$(this).remove();
});
});
});
CSS:
.blank {
display:block;
padding:4px;
background:#c3c3c3;
position:absolute;
}
table tr td {
overflow:visible;
position:relative;
}
table tr {
cursor:pointer;
}
这是一个jsfiddle ,但请注意,我没有对外观进行样式化,并且必须更新有关左键单击的 javascript 代码。
关于javascript - 右键单击不使用单击功能的表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11857978/