问题描述
代码:
var link = $(< a>< / a>);
link.attr(href,/dostuff.php);
link.attr(target,_blank);
link.click();
属性设置正确:
var link = $(< a>< / a>);
link.attr(href,/dostuff.php);
link.attr(target,_blank);
var linkcheck = link.wrap('< p>')。parent()。html();
console.log(linkcheck);
返回:
< a href =/ dostuff.phptarget =_ blank>< / a>
没有错误
更新
我试图附加它,绑定点击它,点击它并删除它
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();
正在执行点击操作,但默认操作(打开链接)不是..
更新2
我找到了解决方案:提交< form>
!
我有答案。显然,jQuery不支持
创建和提交表单的工作原理很好(但在 Chrome 26
, FF 20
和 IE 8
):
var form = $(< form>< /形式>中);
form.attr(
{
id:newform,
action:https://google.nl,
method:GET,
target:_blank//在新窗口/ tab中打开
});
$(body)。append(form);
$(#newform)。submit();
$(#newform)。remove();
它的作用如下:
- 创建表单
- 给它属性
- 将其附加到DOM,以便可以提交
- 提交
- 从DOM中删除表单
现在你有新的标签/窗口加载(或任何您想要的URL,只需替换它)。不幸的是,当您尝试以这种方式一次打开多个窗口时,尝试打开第二个窗口时会收到一个弹出窗口阻止的消息栏(第一个窗口仍然打开)。
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.
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:
- Create a form
- Give it attributes
- Append it to the DOM so it can be submitted
- Submit it
- 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).
这篇关于打开新的窗口/选项卡,而不使用`window.open`或`window.location.href`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!