0

我试图确定一个元素是否是另一个具有特定属性的选民的后代。到目前为止,当值为 true 时我没有问题,但是TypeError: undefined is not a function (evaluating 'node.hasAttribute(attribute)')当 hasAttribute 为 false 时我得到了。有任何想法吗?

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/

4

1 回答 1

0

Your loop goes from the child.parentNode up to the document, and on each node it uses the hasAttribute method of the Element interface. However, Documents are plain Nodes that do not implement this interface.

Change your condition to

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

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

于 2015-01-19T12:43:34.230 回答