簡體   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