最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - setAttribute target _blank doesn't open in new tab - Stack Overflow

matteradmin6PV0评论
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?

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?

Share Improve this question edited Feb 22, 2016 at 21:57 stark 2,2562 gold badges24 silver badges35 bronze badges asked Feb 22, 2016 at 21:45 fauverismfauverism 1,9924 gold badges35 silver badges61 bronze badges 2
  • I think it requires an href attribute. – Yogi Commented Feb 22, 2016 at 21:48
  • This doesn't seem plete enough to do anything at all. – durbnpoisn Commented Feb 22, 2016 at 21:50
Add a ment  | 

2 Answers 2

Reset to default 4

Anchor elements without href attributes aren't linking to anywhere, so they aren't links, so clicking on one doesn't do anything.

When I added setAttribute("href", "something") it triggered a new window in my test.

IF you also set an href attribute

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

Then when you call a.click() what you will most likely see (in Chrome and Canary) is that the browser will block this popup. 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.

Post a comment

comment list (0)

  1. No comments so far