繁体   English   中英

不同HTML页面上的相同DOM元素

[英]Same DOM elements on different HTML pages

我认为我的问题有点愚蠢,但我有一个问题。 有一些html页面,例如:index.html和rooms.html等。还有一个main.js文件,其中包含所有.html页面的脚本。 问题是我有一个变量,例如

const HTMLelement = document.querySelector('.className');

以及一些与此HTMLelement一起使用的功能。 但是,此元素仅在index.html页面上,并且当im在rooms.html页面上时,出现错误,导致未定义HTMLelement且其他脚本不存在(重要的是,导致一些按脚本构建html。) ,在main.js中,我为所有页面提供了脚本,因此无法创建新的.js文件...那么,为不同的html页面separate脚本的最佳方法是什么?

在这里,您有几种解决问题的方法

为每个页面创建特定的单独脚本

  • rooms.html-> rooms.js
  • index.html-> index.js

在做某事之前检查节点的存在

if(document.querySelectorAll('.className').length == 0){
     // do things
}

在执行操作之前检查当前页面

if(window.location.pathname.indexOf('rooms.html') != -1){
     // do things
}

希望能帮助到你

在尝试使用某个元素之前,请始终对其进行验证。

 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.

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