[英]Cannot figure out where to load javascript file
HTML HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Game</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="script.js"></script>
</head>
<body>
<div class="container">
<table class="table ">
<tr>
<td id="1">a</td>
<td id="2">a</td>
<td id="3">a</td>
<td id="4">a</td>
</tr>
<tr>
<td id="5">a</td>
<td id="6">a</td>
<td id="7">a</td>
<td id="8">a</td>
</tr>
<tr>
<td id="9">a</td>
<td id="10">a</td>
<td id="11">a</td>
<td id="12">a</td>
</tr>
<tr>
<td id="13">a</td>
<td id="14">a</td>
<td id="15">a</td>
<td id="16">a</td>
</tr>
</table>
</div>
</body>
function startFunction() {
var table = document.querySelector('#table');
var table_cells = table.querySelectorAll('td');
}
window.onload = function() {
startFunction();
};
I keep getting an error of "uncaught typeError: cannot read property 'querySelectorAll' of null." 我不断收到“未捕获的typeError错误:无法读取null的属性'querySelectorAll'”的错误。
I think this has to do with the fact when I'm calling a function that tries to grab said element node before it exists perhaps? 我认为这与以下事实有关:当我调用一个试图在该元素节点存在之前尝试抓住该元素节点的函数时,该事实与事实有关?
I'm loading my Javascript file in the <head>
section of my HTML file so I added a window.onload
function to make sure everything is loaded before the page runs. 我将Javascript文件加载到HTML文件的<head>
部分中,因此添加了window.onload
函数以确保在页面运行之前已加载所有内容。 However, I still keep getting this error. 但是,我仍然不断收到此错误。
Take a look at this line in your JavaScript: 看看JavaScript中的这一行:
var table = document.querySelector('#table');
The pound-sign indicates an ID , and so your javascript is looking for an element with the ID of "table". 井号表示ID ,因此您的JavaScript正在寻找ID为“表格”的元素。
But, if you look at your table, it doesn't have an ID; 但是,如果您查看自己的桌子,它没有ID。 only class . 只有班级 。
The solution is to give your <table>
an ID of "table" so that the javascript properly finds it: 解决方案是给您的<table>
一个ID为“ table”,以便javascript正确找到它:
<table id="table">
The table is missing id
attribute. 该表缺少id
属性。 Instead, it has class attribute. 相反,它具有类属性。 Fix by adding id
通过添加id
修复
<table class="table" id="table">
Or modify your query selector to select by class: 或修改查询选择器以按类进行选择:
var table = document.querySelector('.table');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.