Handling clicks on links myself - JQuery Mousedown

2019-08-14 13:46发布

问题:

I want to handle clicks on specific elements myself. So that if I click it with the left mousebutton it opens the link in the current tab and if I click it with the middlebutton, it opens it in a new tab. I want to do this by getting the href attribute from the link and use window.open()

Is this even possible without running into popupblocker issues?

So for starters I tried to prevent the opening of the link.

HTML:

<a href="somelink.php" class="prev_cl"><img src="someimg.png" /></a>

Javascript:

$(function() {
    $('.prev_cl').on('mousedown', function(e){
        return false;
    });
})

But even this isn't working, it still opens the link. If I put an alert before "return false" it actually doesn't trigger the click and shows the alertbox. But who wants an alert box everytime they click a link?

I also tried using both mouseup and mousedown events, but that didn't work either

Another thing I tried was putting the return false to the element itself, meaning:

 <a href="somelink.php" onclick="return false" class="prev_cl"><img src="someimg.png" /></a>

Then on the javascript part I added window.open() to it

But 1) clicking with middlemousebutton still works and 2) Firefox blocks the opening of the window because it thinks it is a popup

回答1:

event.preventDefault() of jQuery can be used to prevent the default action of an event, in this case the click.

http://api.jquery.com/event.preventdefault

Also, you can catch middle (or any) mouse button like this: Jquery: detect if middle or right mouse button is clicked, if so, do this:



回答2:

Put your handler on the click event, not mousedown.

$(function() {
    $('.prev_cl').on({
        'click': function(e){
          	if (e.which == 1) {
                var button = "left";
            } else {
                button = "middle";
            }
            console.log(button+" click");
            console.log(e.which);
            e.preventDefault();
        },
        'contextmenu': function(e) {
            console.log("right click");
            console.log(e.which);
            e.preventDefault();
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="somelink.php" class="prev_cl"><img src="someimg.png" /></a>