简体   繁体   中英

Javascript not executing when right clicked into new tab

Here is my simple code

 function goto() {
        /* Some code to be executed */
        if (a == "1")
              location.href = "http://www.google.com";
        else
              location.href = "http://www.example.com";
    }

And here is html

<a href="#" onclick="goto();">Hello</a>

this works perfectly fine when i click normally but if i right click it and open in a new tab it doesn't execute.

try this:

<a href="javascript:goto()">Hello</a>

 function goto() {
        /* Some code to be executed */
        window.open("http://www.google.com");
    }

if you want to open in new tab on mouse right click,

<a href="http://www.google.com">Hello</a>

hit mouse right click and open in new tab

OR

u can try this:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="jquery.min.js"></script>
    <script>
        function goto() {
            window.location = "http://www.google.com";
        }
        document.addEventListener('DOMContentLoaded', function () {
            document.getElementsByTagName('a')[0].addEventListener('contextmenu', function (ev) {
                ev.stopPropagation();
                ev.preventDefault();
                goto();
            });
            document.getElementsByTagName('a')[0].addEventListener('click', function (ev) {
                goto();
            });
        }, false)

    </script>
</head>
<body>
<a href="#">Hello</a>
</body>
</html>

Try something like this:

<a href="#" id="myId">Hello</a>

<script>
document.getElementById('myId').addEventListener('contextmenu', function(ev){
    gotoFunc(ev);
});

function gotoFunc(ev){
    //run this when right clicked over #myId element
}
</script>

do it like this:

 function changeDest(elem) {
        /* Some code to be executed */
        if (a == "1")
              elem.href = "http://www.google.com";
        else
              elem.href = "http://www.example.com";
    }

 <a href="#" onmousedown="changeDest(this);">Hello</a>

you can instead use <a href="http://www.google.com" onclick="goto();">Hello</a> This should do the trick. ie adding the url to the href of the anchor tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM