英文:
How do I get my Javascript to work with all views in Javascript/Handlebars.js
问题
Handlebars有一个功能,我可以加载一堆子文档。在主文档内。
在main.handlebars中,我有我的菜单项,当点击时会加载home.handlebars、license.handlebars等。会发生页面重新加载。
main.handlebars加载了我的index.js文件。
但是这个JS文件会返回一个错误,因为它尝试通过以下方式访问元素:
const dataFromDB = document.querySelector('.elementFromHome')
这个元素位于home.handlebars内。
现在假设我点击一个加载license.handlebars的菜单项。如果它们在home.handlebars中,那么index.js中的所有元素都将返回null。有什么帮助吗?
我的解决方案:
我可能可以将需要用于每个子文档的元素包装在一个if语句中。这样它会在每次页面加载时检查它。但我在寻找更实际的解决方案。谢谢。
应用程序使用MEVN堆栈。
英文:
Handlebars has a feature where I can load a bunch of subdocuments. Inside the main document.
Inside main.handlebars I have my menu items that when clicked will load home.handlebars, license.handlebars, etc. A page reload does happen.
main.handlebars loads my index.js file.
But that JS file will return an error because an element it's trying to access via
const dataFromDB = document.querySelector('.elementFromHome')
is inside home.handlebars
Now let's say I click a menu item that loads the license.handlebars. All the elements in index.js will return null if they were in home.handlebars. Any help?
My solution:
I probably could wrap my elements that are needed for each sub-document. In an if statement. So it would check it on each page load. But I looking for a more practical solution. Thank you.
App is using the MEVN stack.
答案1
得分: 1
看起来你可以通过在 node.addEventListener
上使用可选链来修复这个问题。
然后,如果在该页面上 dataFromDB
为 null
,你将不会因尝试访问 null
上的 addEventListener
属性而导致运行时 TypeError。
const dataFromDB = document.querySelector('.elementFromHome')
dataFromDB?.addEventListener('click', () => {
console.log('click')
})
<button class="elementFromHome">button from home</button>
<details>
<summary>英文:</summary>
It seems like you could fix this by using [optional chaining][1] at `node.addEventListener`.
Then if `dataFromDB` is `null` on that page, you won't get a runtime TypeError by attempting to access the `addEventListener` property on `null`.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const dataFromDB = document.querySelector('.elementFromHome')
dataFromDB?.addEventListener('click', () => {
console.log('click')
})
<!-- language: lang-html -->
<button class="elementFromHome">button from home</button>
<!-- end snippet -->
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论