0

我有一个索引页面和一个仪表板,在索引上我只在索引上使用打字机和particlejs,在仪表板上我有一个侧边栏。

如果我拥有所有代码,我会收到错误,因为页面仍在所有页面上寻找打字机和particlejs。

因此,我尝试将每个部分包装在一个周围,if因此计划是如果该类或 id 存在于该页面上,它将仅呈现该 JS。所以我创建了以下代码。

根据groovy_guy的回答编辑了下面的代码

document.querySelector('nav .toggle').addEventListener('click', e => {
  document.querySelector('nav .hidden').classList.toggle('show')
});

let checkTypewriter = document.getElementById('typewriter');
if (checkTypewriter.length > 0) {
  new Typewriter('#typewriter', {
    strings: ['Website Developer', 'Freelancer' , 'System Admin'],
    autoStart: true,
    loop: true
  });
}

let checkParticlesjs = document.getElementsByClassName('particlesjs');
if (checkParticlesjs.length > 0) {
  let particles = Particles.init({
    selector: '.particlesjs',
    color: ['#48F2E3', '#48F2E3', '#48F2E3'],
    connectParticles: true,
    maxParticles: 200
  });
}

let checkSidebar = document.getElementsByClassName('sidebar');
if (checkSidebar.length > 0) {
  user_wants_collapse = false;

  // Fetch all the details element.
  const details = document.querySelectorAll("details");

  // Add the onclick listeners.
  details.forEach((targetDetail) => {
    targetDetail.addEventListener("click", () => {
      // Close all the details that are not targetDetail.
      details.forEach((detail) => {
        if (detail !== targetDetail) {
          detail.removeAttribute("open");
        };
      });
    });
  });

  document.querySelector('section').addEventListener('click', (ev) => {
    // close any open details elements that this click is outside of
    let target = ev.target;
    let detailsClickedWithin = null;

    while (target && target.tagName != 'DETAILS') {
      target = target.parentNode;
    };

    if (target && target.tagName == 'DETAILS') {
      detailsClickedWithin = target;
    };

    Array.from(document.getElementsByTagName('details')).filter(
      (details) => details.open && details != detailsClickedWithin
    ).forEach(details => details.open = false);

    // if the sidebar collapse is true and is re-expanded by clicking a menu item then clicking on the body should re-close it
    if (user_wants_collapse == true && (document.querySelectorAll('.sidebar details'))) {
      document.querySelector('body').classList.add('is--expand');
    };
  });

  // when the sidebar menu is clicked this sets the user_wants_collapse var to true or false and toggles is--expand class on body
  document.querySelector('.sidebar .menu-link').addEventListener('click', () => {
    document.querySelector('body').classList.toggle('is--expand');
    user_wants_collapse = !user_wants_collapse

    document.querySelector('.sidebar').classList.toggle('is--expand');

    // show all text
    document.querySelectorAll('.sidebar .title').forEach((el) => {
      el.classList.toggle('hidden');
    });

    // changing sidebar menu items and menu collapse icons
    const icon = document.querySelector('.menu-link-arrows span');

    if (icon.classList.contains('fa-angle-double-left')) {
      icon.classList.remove('fa-angle-double-left');
      icon.classList.add('fa-angle-double-right');
    } else {
      icon.classList.remove('fa-angle-double-right');
      icon.classList.add('fa-angle-double-left');
    }
  });

  // making sure the sidebar menu items re-expands the sidebar on click
  let x = document.querySelectorAll('.sidebar details');
  let i;

  for (i = 1; i < x.length; i++) {
    x[i].addEventListener('click', () => {
      // changing sidebar menu items and menu collapse icons
      // change menu items and menu collapse icons
      const icon = document.querySelector('.sidebar-drop-parent-arrow span');

      if (icon.classList.contains('fa-chevron-down')) {
        icon.classList.remove('fa-chevron-down');
        icon.classList.add('fa-chevron-up');
      } else {
        icon.classList.remove('fa-chevron-up');
        icon.classList.add('fa-chevron-down');
      }

      if (document.querySelector('body').classList.contains('is--expand')) {
        document.querySelector('body').classList.remove('is--expand');
      };
    });
  };
};

加载 JS 时,我没有收到任何控制台错误,但我没有看到 JS 的任何结果。

4

2 回答 2

1

你为什么不使用querySelector()?我认为这在您的代码库中更加统一。此外,我看到您只关心一个元素而不是元素列表,因此这种方法是理想的,因为它获取遇到的第一个元素。

const checkTypewriter = document.querySelector('#typewriter')
if (checkTypewriter) {
  // Element with an ID 'typewriter' exist in the DOM.
}

const checkParticlesjs = document.querySelector('.particlesjs')
if (checkParticlesjs) {
  // Element with a class named "particlesjs" exist in the DOM.
}

此外,请确保在附加事件侦听器之前检查元素是否存在:

const toggleNav = document.querySelector('nav .toggle')

if (toggleNav) {
  toggleNav.addEventListener('click', (e) => {
    document.querySelector('nav .hidden').classList.toggle('show')
  });
}
于 2021-10-28T12:49:00.450 回答
0

对于 Javascript:

var checkTypewriter = document.getElementsByClassName('typewriter');
    if (checkTypewriter.length > 0) {
        // Here write your code
    }

var checkParticlesjs = document.getElementsByClassName('particlesjs');
    if (checkParticlesjs.length > 0) {
        // Here write your specific code
    }

对于 JQuery:

    if ($("#typewriter")[0]){
        // Here write your code
    } 

    if ($(".particlesjs")[0]){
        // Here write your specific code
    } 

这是您可以检查您的课程是否存在的方法,

于 2021-10-28T12:10:15.820 回答