如何在不调用onclick的情况下打开新窗口上的链接

How to open link on new window without calling onclick

本文关键字:新窗口 窗口 链接 调用 情况下 onclick      更新时间:2023-09-26

我有如下HTML代码:

 <a href="#" onclick="reloadPage()">Text</a>

当用户点击链接上的"鼠标左键"时,应该调用reloadPage()。

但当用户在链接上使用"Ctrl+click"或"middle button"点击时,我想打开一个新窗口而不重新加载页面()。

我该怎么做?

您可以在此处引用。这是我的代码

<a href="#" id="test" onclick="reloadPage(event)">Click Me</a>
<script>
$(document).ready(function() {
$(document).keydown(function(event){
    if(event.which==17)
        cntrlIsPressed = true;
});
$(document).keyup(function(){
    cntrlIsPressed = false;
});
});
var cntrlIsPressed = false;

function reloadPage(mouseButton,event)
{
        //event.preventDefault();
    if( event.which == 2 ) {
        //todo something
      //window.open($("#test").attr("href"));
      alert("middle button"); 
      return false;
    }
    if(cntrlIsPressed)
    {
         //window.open($("#test").attr("href"));
        // ctrl + click 
        return false;
    }
    //todo something
    window.location.href = $("#test").attr("href");
    return true;
}
</script>

您可以简单地将a标签上的href属性设置为当前页面url,这样,当用户单击它时,它将打开同一页面(重新加载),如果单击鼠标中键,它将在新标签中打开同一页。

如果你想在多个页面上使用它,那么你可以将javascript中的href设置为当前页面的url,比如这个

document.getElementById('myId').href = location.href

您可以尝试这种方法(html):

<a href="#" id="mylink">Text</a>

Javascript:

$(function () {
        $("#mylink").click(function (event) {
            if ((event.button == 0 && event.ctrlKey) || event.button == 1) {
                event.preventDefault();
                window.open("http://www.google.com");
            }
            else
                if (event.button == 0)
                    window.location.reload();                                
        });
});

我有两个选项。纯javascript,并使用jquery。

这是完整的代码。

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $('#jqueryStyle').mousedown(function(e){
            //3 is right click
            if(e.which == 3){
               window.open("http://www.w3schools.com");
            //1 is for click
            }else if(e.which == 1){
                reloadPage();
            }
        });
    });
    function reloadPage(){
       location.reload();
    }
    function onMouseDown(e,obj){
        e = e || window.event;
        //3 is for right click
        if(e.which == 3){
            window.open("http://www.w3schools.com");
        //1 is for click
        }else if(e.which == 1){
            reloadPage();
        }
    }
    </script>
</head>
<body>
     <a href="#" id="jqueryStyle">JQuery Code</a ><br/>
     <a href="#" onmousedown="onMouseDown(event,this)">Pure Javascript Code</a >
</body>
</html>

希望能有所帮助。