尝试使用 hasAttribute 识别父级的后代时出现未定义的错误

Undefined error when trying to identify descendant of parent using hasAttribute

本文关键字:后代 错误 未定义 hasAttribute 识别      更新时间:2023-09-26

我正在尝试确定一个元素是否是另一个具有特定属性的选举的后代。到目前为止,当值为真时我没有问题,但是当 hasAttribute 为假时,我会得到TypeError: undefined is not a function (evaluating 'node.hasAttribute(attribute)')。有什么想法吗?

document.body.addEventListener('touchmove', function(event) { stopScroll(event); });
var stopScroll = function(event) {
    var target = event.target;
    var parent = target.parentNode;
    if (isDescendantOf.attribute('data-scroll', target)) {
    } else {
        event.preventDefault();
    }
};
var isDescendantOf = {};
isDescendantOf.parent = function(parent, child) {
    var node = child.parentNode;
    while (typeof node !== 'undefined') {
        if (node == parent) {
            return true;
        }
        node = node.parentNode;
    }
    return false;
};
isDescendantOf.tag = function(tag, child) {
    var node = child.parentNode;
    while (typeof node !== 'undefined') {
        if (node.tagName == tag) {
            return true;
        }
        node = node.parentNode;
    }
    return false;
};
isDescendantOf.attribute = function(attribute, child) {
    var node = child.parentNode;
    while (node !== null) {
        console.log(typeof node);
        if (node.hasAttribute(attribute) === true) {
            return true;
        }
        node = node.parentNode;
    }
    return false;
};

这是小提琴,尽管由于某种原因它表现得更奇怪:http://jsfiddle.net/x95tgmkn/

你的循环从child.parentNodedocument,在每个node它都使用 Element 接口的 hasAttribute 方法。但是,Document 是未实现此接口的普通Node

将您的状况更改为

while (node != null && node.nodeType == 1)

node.nodeType != 9typeof node.hasAttribute == "function".