Opening new window/tab without using `window.open` or `[removed].href`

后端 未结 3 1788
失恋的感觉
失恋的感觉 2020-12-11 10:09

I want to generate a link that is clicked right after creating, but nothing happens

Code:

var link = $("");
link.attr(&quo         


        
相关标签:
3条回答
  • 2020-12-11 10:49

    I have the answer. Apparently jQuery doesn't support the default behavior of links clicked programmatically

    Creating and submitting a form works really well though (tested in Chrome 26, FF 20 and IE 8):

    var form = $("<form></form>");
    form.attr(
    {
        id     : "newform",
        action : "https://google.nl",
        method : "GET",
        target : "_blank"        // Open in new window/tab
    });
    
    $("body").append(form);
    $("#newform").submit();
    $("#newform").remove();
    

    What it does:

    1. Create a form
    2. Give it attributes
    3. Append it to the DOM so it can be submitted
    4. Submit it
    5. Remove the form from the DOM

    Now you have a new tab/window loading "https://google.nl" (or any URL you want, just replace it). Unfortunately when you try to open more than one window at once this way, you get an Popup blocked messagebar when trying to open the second one (the first one is still opened).

    0 讨论(0)
  • 2020-12-11 10:58

    Regarding your updated script: If you get the selector right ($("#linky")) it works.

    var link = $("<a id='linky'>Hello</a>");
    link.attr("href", "/dostuff.php");
    link.attr("target", "_blank");
    $("body").append(link);
    $("#linky").on("click", function() {alert("hai");});
    $("#linky").click();
    $("#linky").remove();
    
    0 讨论(0)
  • 2020-12-11 11:10
    var link = $("<a id='linky'></a>");
    link.attr("href", "/dostuff.php");
    link.attr("target", "_blank");
    $("body").append(link);
    $("linky").live("click", function() {alert("hai"); $(this).remove()});
    $("linky").click();
    //$("linky").remove();
    

    So you actually react on the click event. And YES! The question is why would you want to do this?

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