首页 > 解决方案 > 仅在存在锚标记时运行 JavaScript

问题描述

我在下面写了一小段 JavaScript,为了便于访问,从我的菜单中移除焦点。然而,在页面加载时,“锚链接”不存在,因此变量“as”返回 NULL。

我希望代码仅在存在 dropdownMenu 锚标记时运行。

const dropdownMenu = document.querySelector('#progressive-nav-more-list');
const as = dropdownMenu.querySelectorAll('a');
const last = as[as.length - 1];

last.addEventListener('blur', () => {
  this.container.classList.remove('opened');
  this.more_list.classList.add('hidden');
  toggleAria(this.more_list, 'aria-expanded');
});

标签: javascripthtml

解决方案


你能在 document.onreadystatechange 中投降吗?

    document.onreadystatechange = function () {
        if (document.readyState == "complete") {
          const dropdownMenu = document.querySelector('#progressive-nav-more-list');
          const as = dropdownMenu.querySelectorAll('a');
          const last = as[as.length - 1];

          last.addEventListener('blur', () => {
            this.container.classList.remove('opened');
            this.more_list.classList.add('hidden');
            toggleAria(this.more_list, 'aria-expanded');
          });    
       }
    }

推荐阅读