[英]DOM, javascript, how to use window open
I have to have separate javasvript and html-files and I'm trying to open a new window when I click on a link, but it is not working. 我必须有单独的javasvript和html文件,当我单击链接时,我试图打开一个新窗口,但是它不起作用。
HTML: HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" href=""/>
<script type="text/javascript" src="java3.js"></script>
</head>
<body>
<a href="#" id="link">Click!</a>
</body>
</html>
Javascript: Javascript:
var a = document.getElementById("link");
a.onclick = function(){
window.open("http://www.google.com");
};
If you open the console you will likely see an error message like: 如果打开控制台,您可能会看到如下错误消息:
TypeError: Cannot set property 'onclick' of null
This is because document.getElementById("link")
is null
. 这是因为
document.getElementById("link")
为null
。
Why is it null
? 为什么它为
null
? It's right there on the page! 就在页面上!
Well, not when this code runs. 好吧,不是在运行此代码时。 The JavaScript code runs before the body is defined.
JavaScript代码在定义主体之前运行。
Either move your script down, or wrap your code in a ready/onload event: 向下移动脚本,或将代码包装在ready / onload事件中:
window.onload = function() {
var a = document.getElementById("link");
a.onclick = function() {
window.open("http://www.google.com");
};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.