简体   繁体   中英

Why does anchor tag not open target in a new window or tab?

Why does the following code fail to open the target in a new window or tab:

<html>
<head>
    <title>Test 2</title>
</head>
<body>
    <a href="javascript:document.write('<!DOCTYPE html><html><head><title>Popup</title></head><body><p>Hello, world!</p></body></html>');" target='_blank'>Click Me</a>.
</body>
</html>

I have a feeling that I'm missing something pretty basic; but, I'm not seeing it.

You can use var win = window.open(null, '_blank'); followed by win.document.write(); to accomplish what you are trying to do.

Example as a link:

<a href="javascript:var win = window.open(null, '_blank');win.document.write('<!DOCTYPE html><html><head><title>Popup</title></head><body><p>Hello, world!</p></body></html>');" target='_blank'>Click Me</a>

Fiddle: http://jsfiddle.net/howderek/m4qhrre2/

The reason your code doesn't work is because you are writing to the current document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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