在没有href详细信息更改的链接上单击(Ctrl+Click)时,停止打开新选项卡



当使用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的详细信息。我该怎么办?

你几乎做到了,更改这个

$('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);')

试试这个,当用户鼠标悬停在上面时看不到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;
});
});
  $('#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'); 
        } 
    });

相关内容

最新更新