尝试使用 hasAttribute 识别父级的后代时出现未定义的错误
Undefined error when trying to identify descendant of parent using hasAttribute
我正在尝试确定一个元素是否是另一个具有特定属性的选举的后代。到目前为止,当值为真时我没有问题,但是当 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.parentNode
到document
,在每个node
它都使用 Element
接口的 hasAttribute
方法。但是,Document
是未实现此接口的普通Node
。
将您的状况更改为
while (node != null && node.nodeType == 1)
或node.nodeType != 9
或typeof node.hasAttribute == "function"
.
相关文章:
- Node.js v6.2.0类扩展不是函数错误
- Jquery菜单操作不稳定,定位不正确,存在一般错误
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 试图在引导模式内动态生成图表,得到offsetWidth错误
- 为什么会出现错误;未捕获的类型错误:undefined不是函数;
- 我如何修复包含在captcha的addthis中的错误
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- Webpack/Rect:遵循egghead.io教程,但出现错误:您可能需要一个合适的加载程序来处理此文件类型
- CKFinder 3为所选文件返回错误的URL
- 同位素库错误:未捕获错误无布局模式包装生产线8
- 铬:“;未捕获的语法错误:意外的标记:"
- 如何通过自己获得Chrome扩展的用户反馈/错误报告
- 相位器状态未捕获参考错误
- /undefined在我的404错误日志中多次出现
- Javascript未捕获语法错误意外的标识符错误
- javascript:如何在antlr生成的Lexer中进行错误处理
- Angularjs工厂注入错误
- 尝试使用 hasAttribute 识别父级的后代时出现未定义的错误
- 父后代 jquery 选择器中出现奇怪的错误