【问题标题】:Same DOM elements on different HTML pages不同 HTML 页面上的相同 DOM 元素
【发布时间】:2018-01-19 15:14:43
【问题描述】:

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

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

和一些与这个 HTML 元素一起工作的函数。但是,这个元素只在 index.html 页面上,当我在 rooms.html 页面上时,我有一个错误,导致 HTMLelement 没有定义并且其他脚本不存在(它很重要,导致一些 html 由脚本构建。)另外,在 main.js 我有所有页面的脚本,所以我不能创建新的 .js 文件...... 那么,separate 不同 html 页面的脚本的最佳方式是什么?

【问题讨论】:

  • 为什么不在尝试对其执行任何进一步操作之前检查该元素是否确实存在...?
  • 所以,我只需要检查 if(HTMLelement) { //some code } 是否可以?
  • “另外,在 main.js 中我有所有页面的脚本,所以我不能创建新的 .js 文件...”没有更多信息,这个论点不成立
  • 为什么main.js 包含所有页面中javascript 中的all?只需将其分成更多文件。制作具有repeatable content 功能的one file,并将其包含在需要它的all the HTML 文件中。然后在需要的地方使用page specific functions 制作other files,并将它们仅添加到HTML pages for which they were written
  • 把你的 JS 分成几部分。一个脚本用于您希望在所有页面上共享的功能,每个页面一个脚本负责处理特定于页面的事情。

标签: javascript html dom code-separation


【解决方案1】:

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

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

  • 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
}

希望对你有帮助

【讨论】:

    【解决方案2】:

    在您尝试使用某个元素之前,请始终验证它是否存在。

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 2019-04-14
      • 2018-05-11
      • 2021-07-27
      • 2013-03-15
      相关资源
      最近更新 更多