Chrome console 出现的 Uncaught TypeError: Cannot read property 'attributes' of undefined 应该怎么排查呢?

2015-11-11 18:03:49 +08:00
 isbase
Uncaught TypeError: Cannot read property 'attributes' of undefined
Uncaught TypeError: Cannot read property 'nodeType' of undefined



这是出问题代码片段
element = document.getElementsByTagName('*');
var l = element.length;
for (var j = 0; j < l; j++) {
if (element[j].attributes['class'] != undefined && element[j].attributes['class'].value === 'github') {
element = element[j];
}
}




我在 console 里手工测试 document.getElementsByTagName('*')[key].attributes['class'] != undefined && document.getElementsByTagName('*')[key].attributes['class'].value === 'github' 是没问题的
循环中会出现的元素我都在console手工测试过,所以元素明明都是可以使用attributes和nodeType的
5626 次点击
所在节点    JavaScript
11 条回复
tudou527
2015-11-11 18:35:33 +08:00
这个报错不是已经很明确了吗?你要找 xxx.attributes 和 ooo.nodeType ,但是 xxx 和 ooo 不存在。
oxyflour
2015-11-11 18:38:36 +08:00
element = element[j];

说一下你想对 element 做什么奇怪的事情?
jings
2015-11-11 19:28:51 +08:00
@tudou527 泥垢了😅
^﹏^
用原生的 DOM 写是有多累。
aivier
2015-11-11 19:35:30 +08:00
@jings 我觉得比带几百 K 的库好多了,楼主写法比较奇特...所以看着很累,让我写的话,
document.get....("*").forEach(func (){
});
isbase
2015-11-11 22:00:37 +08:00
@tudou527 就是疑惑为什么会找不到呢 我在 chrome 控制台手工输入是可以找到的
isbase
2015-11-11 22:04:31 +08:00
@oxyflour
@tudou527
@aivier


完整代码

function $(selector) {
var str = selector.split(' '),
temp,
element = document;
for (var i = 0; i < str.length; i++) {//ID
if (str[i].indexOf('#') === 0) {
temp = str[i].replace('#', '');
element = element.getElementById(temp);
}
else if (str[i].indexOf('.') === 0) {//Class
temp = str[i].replace('.', '');
element = element.getElementsByClassName(temp)[0];
}
else if (str[i].indexOf('#') === -1 && str[i].indexOf('.') === -1 && str[i].indexOf('[') === -1) {//Tag
element = element.getElementsByTagName(str[i])[0];
}
else if (str[i].indexOf('[') === 0 && str[i].indexOf('=') === -1) {//属性
temp = str[i].replace('[', '').replace(']', '');
for (var element = element.getElementsByTagName('*'), j = 0; j < element.length; j++) {
if (element[j].hasAttribute(temp) === true) {
element = element[j];
}
}
}
else {//属性值
temp = str[i].replace('[', '').replace(']', '');
temp = temp.split('=');
element = element.getElementsByTagName('*');
var l = element.length;
for (var j = 0; j < l; j++) {
if (element[j].attributes[temp[0]] != undefined && element[j].attributes[temp[0]].value === temp[1]) {
element = element[j];
}
}
}
}
return element;
}
xwartz
2015-11-11 22:21:01 +08:00
= = 打个断点就可以查看哪里不对啊。。这样的代码格式,谁愿意看。。
isbase
2015-11-11 22:26:17 +08:00
@xwartz 回复不能用 Markdown
Slienc7
2015-11-12 09:24:26 +08:00
可以 gist 贴代码
逐步 console.log 出来即可
isbase
2015-11-12 10:32:42 +08:00
xwartz
2015-11-12 13:17:02 +08:00
@isbase = = 运行了下,没报错

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/235418

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX