简体   繁体   English

特定页面上不存在元素

[英]Element does not exists on specific page

I've created a website that has index.html and quiz.html, one style.CSS and one app.JavaScript.我创建了一个网站,其中包含 index.html 和 quiz.html,一个 style.CSS 和一个 app.JavaScript。

I have added some functions in the JS that refer to both pages.我在 JS 中添加了一些引用这两个页面的函数。 Lets say: Page 1 index.html: the app.js has an event listener to show a box on click.让我们说: Page 1 index.html: app.js 有一个事件侦听器,可以在单击时显示一个框。 That box then has a button to move to quiz.html (all works fine).然后那个框有一个按钮可以移动到 quiz.html(一切正常)。 Page 2 quiz.html: on JavaScript I have functions to make the quiz run.第 2 页 quiz.html:在 JavaScript 我有运行测验的功能。 The problem is that the code breaks before it gets to the functions for the quiz, with a line referring to the first page.问题是代码在到达测验函数之前就中断了,其中一行指向第一页。

Error: app.js:14 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at app.js:14:35

Line 14 is document.getElementById('btnPlay').addEventListener('click', openBox) , that refers to an element within index.html, not the page I am now quiz.html.第 14 行是document.getElementById('btnPlay').addEventListener('click', openBox) ,它指的是 index.html 中的一个元素,而不是我现在 quiz.html 中的页面。

I understand why, because on this current page we don't have a reference to it.我明白为什么,因为在当前页面上我们没有对它的引用。 But I have read in many places that is usually better to use one app.js file and not one per html page.但是我在很多地方都读过,通常最好使用一个 app.js 文件,而不是每个 html 页一个。 How do we make this work?我们如何进行这项工作? Any suggestions?有什么建议么?

On some page B you don't have that #btnPlay Element therefore document.getElementById('btnPlay') equals undefined .在某些页面B上,您没有#btnPlay元素,因此document.getElementById('btnPlay')等于undefined And you cannot assign an event listner to it: undefined.addEventListener .而且您不能为其分配事件监听器: undefined.addEventListener

To make sure that element exists — before moving forward确保该元素存在——在继续之前
use Optional Chaining ?.使用可选链接?. . .

document.getElementById('btnPlay')?.addEventListener('click', openBox)

otherwise on page B the "#btnPlay" is not found and your JavaScript will break.否则在页面B上找不到“#btnPlay”,您的 JavaScript 将中断。


Another "old" way to tackle that issue would've been using a statement:解决该问题的另一种“旧”方法是使用声明:

const EL_btnPlay = document.querySelector("#btnPlay"); 
if (EL_btnPlay) EL_btnPlay.addEventListener("click", openBox);

where the aforementioned is just a shorthand to do the same.前面提到的只是做同样事情的简写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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