简体   繁体   English

在所有页面上运行document.getElementById('age')的App.js文件? 我如何包含这个

[英]App.js file running document.getElementById('age') on all pages? How do I contain this

I have an app.js file that contains all my JS for all site pages. 我有一个app.js文件,其中包含所有网站页面的所有JS。 Within the app.js file is a function for age. app.js文件中包含年龄函数。 The function runs fine on the page with the class of '.age'. 该函数在类为“ .age”的页面上运行良好。 But what is the best approach to avoid this being run on all other pages? 但是,最好的方法是避免在所有其他页面上运行该方法?

var start = new Date('09/20/1991 06:00 AM');
  var timer;

  function age() {
    var now = new Date();
    var age = now.getTime() - start.getTime();
    var year = (age / 31556926000);
    document.getElementById('age').innerHTML = year.toFixed(9);
  }
  timer = setInterval(age, 1);

Thank you and sorry if this is a silly question. 谢谢,如果这是一个愚蠢的问题,对不起。

You can check if the element exists and only then register the function: 您可以检查元素是否存在,然后注册该功能:

let ageElement = document.getElementById('age');

// Check the age element exists
if(ageElement){
  var start = new Date('09/20/1991 06:00 AM');
  var timer;

  function age() {
    var now = new Date();
    var age = now.getTime() - start.getTime();
    var year = (age / 31556926000);
    ageElement.innerHTML = year.toFixed(9);
  }
  timer = setInterval(age, 1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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