右键单击不使用单击功能的表行

时间:2012-08-08 05:08:04

标签: javascript jquery

我有一个表和这段代码来查找一个href并使整行可以点击:

$(document).ready( function() {

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

然而,有一个问题,而我的右键点击不提供“新标签中的打开链接”选项和窗口等等正常的href链接。

使用div而不是table不是一种选择。

如何解决?

是否有任何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值: $(本).find( “a”)的ATTR(的 “href”);

编辑2:我需要整个tr可点击(作为一个块)。这可以使用上述方法。但是,无法单击该行并选择“在新选项卡中打开链接”。仅当我将鼠标悬停在某个href上时,此选项才可用。但我需要它也是整个行。因此,如果用户想要使用鼠标中键打开多个新选项卡或右键单击并从上下文菜单中选择“在新选项卡中打开”,则可以执行此操作。现在不可能。

2 个答案:

答案 0 :(得分:2)

你为什么不尝试这样的事情:

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代码。

答案 1 :(得分:0)

试试这个

    $('tr th, tr td').wrapInner('<a href="http://example.com"></a>').children('a').click(function() {
   var href = $(this).attr("href"); if(href) { window.location = href; }
});

//如果有任何delegation问题,请尝试此

    $('tr th, tr td').wrapInner('<a class="links" href="http://example.com"></a>');
$('body').delegate('a.links','click',function(e){
e.preventDefault();

   var href = $(this).attr("href"); if(href) { window.location = href; }
});
相关问题