[英]Same DOM elements on different HTML pages
i think my question is a little bit stupid, but I have a problem. 我认为我的问题有点愚蠢,但我有一个问题。 There`sa few html pages, for ex.: index.html and rooms.html etc... And a main.js file with scripts for all .html pages.
有一些html页面,例如:index.html和rooms.html等。还有一个main.js文件,其中包含所有.html页面的脚本。 The problem is that i have a variables, like
问题是我有一个变量,例如
const HTMLelement = document.querySelector('.className');
and some functions to work with this HTMLelement. 以及一些与此HTMLelement一起使用的功能。 But, this element is only on index.html page, and when im on rooms.html page, i have an error, cause HTMLelement is not defined and other script does not exists (its important, cause some html build by script.) Also, in main.js I have scripts for all pages, so I cant create new .js file... So, what is the best way to
separate
scripts for different html pages? 但是,此元素仅在index.html页面上,并且当im在rooms.html页面上时,出现错误,导致未定义HTMLelement且其他脚本不存在(重要的是,导致一些按脚本构建html。) ,在main.js中,我为所有页面提供了脚本,因此无法创建新的.js文件...那么,为不同的html页面
separate
脚本的最佳方法是什么?
Here you have several ways to solve the issue 在这里,您有几种解决问题的方法
Create specific separate script for each page 为每个页面创建特定的单独脚本
Checking the existence of nodes before you do something 在做某事之前检查节点的存在
if(document.querySelectorAll('.className').length == 0){
// do things
}
Checking the current page before you do something 在执行操作之前检查当前页面
if(window.location.pathname.indexOf('rooms.html') != -1){
// do things
}
Hope it helps 希望能帮助到你
Always validate that an element exists before you try to use it. 在尝试使用某个元素之前,请始终对其进行验证。
const oneEl = document.querySelector('.one'); if (oneEl) { oneEl.setAttribute('title', 'This is one'); } // Below I am trying to get an element by the wrong class name. const twoEl = document.querySelector('.two'); if (twoEl) { // This code will not run twoEl.setAttribute('title', 'This is two'); }
<div class="one">One</div> <div class="too">Two</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.