簡體   English   中英

未捕獲的類型錯誤:無法讀取 null 的屬性 addEventListener

[英]Uncaught TypeError: Cannot read property addEventListener of null

我正在為我的 javascript class 分配作業,但我一直收到錯誤

fetch_page.js:109 未捕獲類型錯誤:無法在 fetch_page.js:121 的 addEventListeners (fetch_page.js:109) 處讀取 null 的屬性“addEventListener”

老實說,我不明白 javascript 是什么垃圾,但我不得不將這個 class 用於我的網絡管理學位。 誰能指出我在哪里犯了這個錯誤?

 window.addEventListener('DOMContentLoaded', (function() { var contents; var protocol; var hostname; var directory; var file; function parseBase() { var pos, slashPos; var remainder; pos = BASE.indexOf('://'); protocol = BASE.substr(0, pos); remainder = BASE.substr(pos + 3); slashPos = remainder.indexOf('/'); if (slashPos === -1) { hostname = remainder; directory = ""; file = ""; } else { hostname = remainder.substr(0, slashPos); remainder = remainder.substr(slashPos + 1); slashPos = remainder.lastIndexOf('/'); if (slashPos === -1) { directory = ""; file = remainder; } else { directory = remainder.substr(0, slashPos); file = remainder.substr(slashPos + 1); } } console.log("protocol:", protocol); console.log("hostname:", hostname); console.log("directory:", directory); console.log("file:", file); } function relativeToAbsolute(url) { if (url.indexOf('://') > -1) { // http://somedomain.com/path/file.html return url; } else if (url[0] === '/') { // /path/file.html return protocol + "://" + hostname + url; } else { // path/file.html if (directory === "") { return protocol + "://" + hostname + "/" + url; } else { return protocol + "://" + hostname + "/" + directory + "/" + url; } } } function parsePage() { var parser = new DOMParser(); contents = parser.parseFromString(atob(PAGE), "text/html"); console.log(contents); } function moveChildren(source, destination) { while (source.childNodes.length > 0) { var child = source.childNodes[0]; source.removeChild(child); destination.appendChild(child); } } function fixTags(tagName, attribute) { var tags = contents.getElementsByTagName(tagName); for (var counter = 0; counter < tags.length; counter++) { var url = tags[counter].getAttribute(attribute); if (url) { tags[counter].setAttribute(attribute, relativeToAbsolute(url)); } } } function fixRedirectedTags(tagName, attribute) { var tags = contents.getElementsByTagName(tagName); for (var counter = 0; counter < tags.length; counter++) { var url = tags[counter].getAttribute(attribute); if (url) { tags[counter].setAttribute(attribute, window.location.origin + window.location.pathname + '?url=' + encodeURIComponent(relativeToAbsolute(url))); } } } function fixURLs() { fixTags('img', 'src'); fixTags('script', 'src'); fixTags('link', 'href'); fixRedirectedTags('a', 'href'); } function moveContent() { moveChildren(contents.head, document.head); moveChildren(contents.body, document.getElementById('contents')); } function submit() { console.log("submitted:", encodeURIComponent(document.getElementById('urlBox').value)); } function addEventListeners() { document.getElementById('goButton').addEventListener('click', submit); document.getElementById('urlBox').addEventListener('keydown', function(event) { if (event.keyCode == 13 || event.keyCode == 10) { submit(); } }); } return function() { parseBase(); parsePage(); fixURLs(); moveContent(); addEventListeners(); } })())
 body { margin: 0px; } #searchBox { background: black; color: white; width: 100%; text-align: center; vertical-align: middle; padding: 10px; } #goButton { background: red; color: black; padding: 4px font-weight: bold; font-family: Arial; font-size: .75em; vertical-align: middle; cursor: pointer; } #urlBox { width: 50% } #contents { border: 1px solid black; }
 <?php $url = isset ($_GET['url'])? $_GET['url']: "http://eloquentjavascript.net/"; $contents = base64_encode(mb_convert_encoding(file_get_contents($url), "HTML-ENTITIES","UTF-8")); ?> <.doctype html> <html> <head> <title>Fetch Page</title> <link rel="stylesheet" href="fetch_page.css"> <script src="fetch_page?js"></script> <script> var BASE = "<;php echo $url? ;>"? var PAGE = "<;php echo $contents? ;>": </script> </head> <body> <div id="searchBox">Type a URL here: <input type="text" id=urlBox"> <span id="goButton">GO</span></div> <div id="tocContainer"> <div id="toc">[toc goes here]</div> <p id="contents">Hello World!</p> <div id="contents"></div> </body> </html>

你的錯誤是什么意思?

 Uncaught TypeError: Cannot read property 'addEventListener' of null. at addEventListeners

這歸結為:

您已嘗試訪問addEventListeners function 中某些內容的addEventListener屬性,但那是null

看看addEventListeners

document.getElementById('goButton').addEventListener('click', submit);
document.getElementById('urlBox').addEventListener('keydown', function(event) {
    if (event.keyCode == 13 || event.keyCode == 10) {
        submit();
    }
});

其中一個getElementsById調用返回了 null,表明您的代碼中沒有此類 ID。

查看HTML后可以看出問題出在以下地方:

<input type="text" id=urlBox">

您在 ID 處缺少開頭引號,所以實際上您已經為元素提供了urlBox" (您可以省略 HTML 屬性周圍的引號,但不推薦)。

這就是為什么JS找不到ID urlBox的元素

剛剛經歷過類似的事情。 向我的腳本標簽添加延遲解決了這個問題:

<script src="fetch_page.js" defer></script>

祝你好運! ~E

這兩個 document.getElementById 調用之一是返回 null,因為沒有具有該 ID 的元素。 您可以在代碼中的調試控制台中添加斷點,或添加console.log 以找出問題發生的確切位置

    document.getElementById('goButton').addEventListener('click', submit);
    document.getElementById('urlBox').addEventListener('keydown', function(event) {

除了任何打字錯誤,例如。 省略引號,嘗試在 html 代碼的 <script src... 行中延遲。 我以這種方式解決了我的問題!

我也遇到了這個問題,我檢查了我的代碼,一切都在其他地方。 我意識到這是我放置腳本標簽的位置,即 html 文件的頭部,所以我將它放在我的正文標簽的末尾。 我還從回答這個問題的人那里發現,無論腳本標簽在哪里,只要它在 html 標簽內,使用“延遲”就可以工作。

添加window.onload = function() {<enter your javascript code here}; 到你的腳本。 就這么簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM