Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
847 views
in Technique[技术] by (71.8m points)

jquery - Opening new window/tab without using `window.open` or `window.location.href`

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

Code:

var link = $("<a></a>");
link.attr("href", "/dostuff.php");
link.attr("target", "_blank");
link.click();

The attributes are set correctly:

var link = $("<a></a>");
link.attr("href", "/dostuff.php");
link.attr("target", "_blank");
var linkcheck = link.wrap('<p>').parent().html();
console.log(linkcheck);

This returns:

<a href="/dostuff.php" target="_blank"></a> 

No errors


UPDATE

I tried to append it, bind click to it, click it and remove it

var link = $("<a></a>");
link.attr(
{
    id    : "linky",
    href  : "/dostuff.php",
    target: "_blank"
});
$("body").append(link);
$("#linky").on("click", function() { console.log("Link clicked"); });
$("#linky").click();
$("#linky").remove();

The click action is being executed, but the default action (open the link) isn't..


UPDATE2

I have found the solution: creating and submitting a <form>! See my answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...