简体   繁体   English

setAttribute target _blank不在新标签页中打开

[英]setAttribute target _blank doesn't open in new tab

var a = document.createElement('a');
a.setAttribute('target','_blank');
a.click();

The above code doesn't work for me. 上面的代码对我不起作用。 Does setAttribute not work if the click event happens in JavaScript ? 如果click事件在JavaScript发生, setAttribute是否不起作用?

Anchor elements without href attributes aren't linking to anywhere, so they aren't links, so clicking on one doesn't do anything . 没有href属性的锚元素不会链接到任何地方,因此它们不是链接,因此单击一个元素不会执行任何操作

When I added setAttribute("href", "something") it triggered a new window in my test. 当我添加setAttribute("href", "something")它在测试中触发了一个新窗口。

IF you also set an href attribute 如果您还设置了href属性

a.setAttribute('href','https://google.com')

Then when you call a.click() what you will most likely see (in Chrome and Canary) is that the browser will block this popup. 然后,当您调用a.click()时(在Chrome和Canary中)您最有可能看到的是浏览器将阻止此弹出窗口。 This is due to the fact that this is pretty much textbook annoying popup, and since the click was not initiated at first by a click from the user, it is seen as spammy. 这是由于这样的事实,这几乎是教科书上令人讨厌的弹出窗口,并且由于该单击并不是最初由用户的单击引发的,因此被视为垃圾邮件。

If you need to do this, it will usually work if you are triggering the inner "click" from a user initiated (onclick) event handler of some type. 如果您需要执行此操作,则通常是从某种类型的用户启动(onclick)事件处理程序触发内部“ click”操作的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM