middle click (new tabs) and javascript links

前端 未结 7 1888
温柔的废话
温柔的废话 2020-12-10 02:36

I am in charge of a website at work and recently I have added ajaxy requests to make it faster and more responsive. But it has raised an issue.

On my pages, there is

相关标签:
7条回答
  • 2020-12-10 02:51

    Yes. Instead of:

    <a href="javascript:code">...</a>
    

    Do this:

    <a href="/non/ajax/display/page" id="thisLink">...</a>
    

    And then in your JS, hook the link via it's ID to do the AJAX call. Remember that you need to stop the click event from bubbling up. Most frameworks have an event killer built in that you can call (just look at its Event class).

    Here's the event handling and event-killer in jquery:

    $("#thisLink").click(function(ev, ob) {
        alert("thisLink was clicked");
        ev.stopPropagation();
    });
    

    Of course you can be a lot more clever, while juggling things like this but I think it's important to stress that this method is so much cleaner than using onclick attributes.

    Keep your JS in the JS!

    0 讨论(0)
  • 2020-12-10 02:53

    The onclick event won't be fired for that type of click, so you need to add an href attribute which would actually work. One possible way to do this by adding a #bookmark to the URL to indicate to the target page what the required state is.

    0 讨论(0)
  • 2020-12-10 02:56

    I liked Oli's approach, but it didn't discern from left and middle clicks. checking the "which" field on the eventArgs will let you know.

    $(".detailLink").click(function (ev, ob) {
        //ev.which == 1 == left
        //ev.which == 2 == middle
        if (ev.which == 1) {
            //do ajaxy stuff
    
            return false; //tells browser to stop processing the event
        }
        //else just let it go on its merry way and open the new tab.
    });
    
    0 讨论(0)
  • 2020-12-10 03:01

    Possibly, I could provide two links each time, one firing the javascript and another being a real link that would allow for middle click. I presume, one of them would have to be an image to avoid overloading the index.

    0 讨论(0)
  • 2020-12-10 03:04

    It would require some testing, but I believe that most browsers do not execute the click handler when you click them, meaning that only the link is utilized.

    Not however that your handler function needs to return false to ensure these links aren't used when normally clicking.

    EDIT: Felt this could use an example:

    <a href="/Whatever/Wherever.htm" onclick="handler(); return false;" />
    
    0 讨论(0)
  • 2020-12-10 03:10
    <a href="/original/url" onclick="return !doSomething();">link text</a>
    

    For more info and detailed explanation view my answer in another post.

    0 讨论(0)
提交回复
热议问题