单击(Ctrl +单击)链接时停止新选项卡打开而不更改详细信息

时间:2015-11-27 06:29:48

标签: javascript jquery html clicking

我想在使用javascript(jQuery)点击链接时停止新的标签页打开。我找到了这段代码

 <html>
<head>
  <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
</head>
<body>

<h3>CTRL+CLICK is disabled </h3>
<a href="https://www.google.co.in">Google</a>
<a href="https://www.yahoo.com">Yahoo</a>

<script>
$(document).ready(function()
{
    $('a').each(function() {
        var href= $(this).attr('href');
        $(this).attr('href','javascript:void(0);');
        $(this).attr('jshref',href);
    });
    $('a').bind('click', function(e) 
    {
        e.stopImmediatePropagation();           
        e.preventDefault();
        e.stopPropagation();
        var href= $(this).attr('jshref');
        if ( !e.metaKey && e.ctrlKey )
            e.metaKey = e.ctrlKey;
        if(!e.metaKey)
        {
            location.href= href;
        }
        return false;
})

});
</script>

</body>
</html>

此代码将href详细信息更改为jshref。但就我而言,我无法改变href的细节。我该怎么办?

3 个答案:

答案 0 :(得分:1)

你几乎做到了,改变了这个

$('a').bind('click', function(e) 
{
    e.stopImmediatePropagation();           
    e.preventDefault();
    e.stopPropagation();
    var href= $(this).attr('jshref');
    if ( !e.metaKey && e.ctrlKey )
        e.metaKey = e.ctrlKey;
    if(!e.metaKey)
    {
        location.href= href;
    }
    return false;
});

到这个

$('a').bind('click', function(e) 
{
    e.preventDefault();
    var href= $(this).attr('jshref');
    if ( !e.metaKey && e.ctrlKey )
        e.metaKey = e.ctrlKey;
    else
        location.href= href;
}

这是jsfiddle

编辑:我更新了jsfiddle,我刚刚添加了e.preventDefault()并删除了$(this).attr('href','javascript:void(0);')

答案 1 :(得分:0)

试试这个,当用户将鼠标悬停在javascript:void()

上时
$(document).ready(function()
{
    $('a').bind('click', function(e) {
    var href= $(this).attr('href');
    $(this).attr('href','javascript:void(0);');
    $(this).attr('jshref',href);
    var href= $(this).attr('jshref');
    if ( !e.metaKey && e.ctrlKey )
        e.metaKey = e.ctrlKey;
    if(!e.metaKey)
    {
        location.href= href;
    }
    $(this).attr('href',href);
    return false;
});
});

答案 2 :(得分:0)

  $('#a').bind('click', function(e) {      
        e.preventDefault(); // Stop right click on link
        return false;     
    });
    var control = false;
    $(document).on("keyup keydown", function(e) {
        control = e.ctrlKey;
    });
    $("a").on("click", function(e) {
        var href= $(this).attr('href');     
        if (control && href=='javascript:;' || href == 'javascript:void(0);' || href == 'javascript:void();' || href == '#') {
            return false; // Stop ctrl + click on link
        }else {
            window.open(href, '_blank'); 
        } 
    });
相关问题