如果var raster = document.querySelector ("canvas")
位于HTML文件中,则会定义并声明栅格。不过,我想在我的js文件中包含所有内容,只有HTML中的函数调用。当我尝试将var raster...
放入.js文件时,它会不断弹出null
。document.querySelector在.js文件中不起作用
有没有什么办法让document.querySelector
指向关联的HTML文件?
// this doesn't work
//var raster = document.querySelector ("canvas").getContext ("2d");
function drawSquare (w,h) {
raster.fillStyle = "blue";
raster.fillRect (0,0,w,h);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>IFS</title>
<script src="IFS.js"></script>
</head>
<body>
<canvas width="500" height="500"></canvas>
<script>var raster = document.querySelector ("canvas").getContext ("2d");
drawSquare (500,500);</script>
</body>
</html>
什么是IFS.js? – Ouroborus
对不起。最上面的代码块是来自文件IFS.js的复制粘贴。底部的块是IFS.html。 – failure
您的脚本文件位于头部,元素位于主体中,当您将JavaScript放在头部时,元素在尝试在主体中查找元素时尚不存在。 – adeneo