javascript - 仅在存在锚标记时运行 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');
});
解决方案
你能在 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');
});
}
}
推荐阅读
- php - PHPSpreadsheet - 如何创建红色的文本?
- asp.net-core - 如何在 Identity Server 4 中配置“密钥材料”以使用 SQL、KeyVault 或任何其他系统?
- triggers - 使用 Salesforce 中的 APEX 触发器将产品价格复制到自定义字段对象中
- python - 问题读取 Zipfile
- angular - 动态加载模块组件Angular2
- html - 内容显示在全宽视频背景之上而不是下方
- swift - 在 Swift 中“使用无关的 &”
- java - 问题:Bing Imagesarch API 返回图像 url。使用 ImageIO.read(url) 读取返回空指针异常
- excel - 为什么 VBA 在查询完成刷新之前继续运行?
- php - PHP SESSION 处理 - 无效值