首页 > 解决方案 > 如何在两个不同的 id 上使用 document.getElementById

问题描述

我正在尝试使用getEleementById在不同页面上显示具有两个唯一 ID 的两个不同元素。一个用于主索引页面,另一个用于项目页面。下面的代码适用于索引页面,但不适用于项目页面。但是如果我摆脱了animation1中的调用,那么它就可以在项目页面上运行。有什么理由为什么document.getElementById只能使用一次,即使它被两个唯一的 id 调用?

function displayTitle(id) {
  var elem = document.getElementById(id);
  elem.style.display = "block";
}

function animation1() {
  displayTitle("main-bnb-logo");
  var title1 = new TimelineMax();
  title1.staggerFromTo(".title span", 0.5,
  {ease: Back.easeOut.config(1.7), opacity: 0, bottom: -80},
  {ease: Back.easeOut.config(1.7), opacity: 1, bottom: 0}, 0.05);
}

function animation2() {
  displayTitle("project-title-content-wrapper");
  var title2 = new TimelineMax();
  title2.staggerFromTo(".project-title span", 0.5,
  {ease: Back.easeOut.config(1.7), opacity: 0, bottom: -80},
  {ease: Back.easeOut.config(1.7), opacity: 1, bottom: 0}, 0.05);
}

   $(document).ready(function() {
   animation1();
   }, 1000);

   $(document).ready(function() {
   animation2();
   }, 1000);

标签: javascriptjquerygetelementbyid

解决方案


问题解决了。就像 Tapas 在评论中所说的那样,我需要对 displayTitle 函数进行空检查:

更新代码:

function displayTitle(id) {

  var elem = document.getElementById(id);
  if (elem == null) {
    console.log('no id selected');
  } else {
  elem.style.display = "block";
  }
}

function animation1() {
  displayTitle("main-bnb-logo");
  var title1 = new TimelineMax();
  title1.staggerFromTo(".title span", 0.5,
  {ease: Back.easeOut.config(1.7), opacity: 0, bottom: -80},
  {ease: Back.easeOut.config(1.7), opacity: 1, bottom: 0}, 0.05);
}

function animation2() {
  displayTitle("project-title-content-wrapper");
  var title2 = new TimelineMax();
  title2.staggerFromTo(".project-title span", 0.5,
  {ease: Back.easeOut.config(1.7), opacity: 0, bottom: -80},
  {ease: Back.easeOut.config(1.7), opacity: 1, bottom: 0}, 0.05);
}

$(document).ready(function() {
animation1();
animation2();
}, 1000);

推荐阅读