我引用了一个元素,baseElement,并且我想查找某个 HTML 数据属性是否存在于其祖先之一的某处,并在找到时获取它的值。如果该属性存在于多个祖先上,我只想要最密切相关的那个上的属性。
我设计了一个循环,由父母启动并检查该属性是否存在。假设的第一个父级baseElement不为空。
let currentElement = baseElement.parentElement;
let foundAttribute = false;
let valueOfAttribute = null;
do {
foundAttribute = currentElement.hasAttribute('html-attribute');
if (foundAttribute) {
valueOfAttribute = currentElement.getAttribute('html-attribute');
} else {
currentElement = currentElement.parentElement;
}
} while (!foundAttribute && currentElement);
Run Code Online (Sandbox Code Playgroud)
我想看看是否有一种更有效、更雄辩或更易于编码的方式来做到这一点。请,只有纯 JavaScript 答案。
我想看看是否有一种更有效、更雄辩或更易于编码的方式来做到这一点。
肯定有。见面closest()
let ancestor = baseElement.closest('[html-attribute]');
let attr_val = ancestor ? ancestor.getAttribute('html-attribute') : null;
Run Code Online (Sandbox Code Playgroud)
closest()需要一个选择器,就像querySelector和类似的方法一样。
| 归档时间: |
|
| 查看次数: |
174 次 |
| 最近记录: |