现在这已经让我感到压力了3个晚上......我不知道为什么它在IE9中工作但不是IE8。当我在IE8上运行它时,我一直收到这个错误:
SCRIPT5007:无法获取属性'src'的值:object为null或undefined
当我尝试调试时,我认为这一行是原因 - >
var map_locations = [], container = document.getElementById('renting-map-js'),
c = container.children, l = c.length, i, obj, p, m, j;
//loop through all child nodes
for ( i = 0; i < l; i++) {
obj = {};
//highlights this line
obj.img = c[i].getElementsByTagName('img')[0].src;
p = c[i].getElementsByTagName('p');
m = p.length;
for ( j = 0; j < m; j++)
obj[p[j].className] = p[j].firstChild.nodeValue;
map_locations[i] = obj;
console.log(obj);
}
答案 0 :(得分:3)
在IE6-8中,.children also returns comment nodes。由于注释节点不能有子节点,因此它们也不能包含具有src属性的图像,从而导致您的错误。
jQuery可以解决这个问题:
var map_locations = [],
container = document.getElementById('renting-map-js'),
c = $(container).children().get(),
l = c.length,
i, obj, p, m, j;
//loop through all child nodes
for (i = 0; i < l; i++) {
obj = {};
obj.img = c[i].getElementsByTagName('img')[0].src;
p = c[i].getElementsByTagName('p');
m = p.length;
for (j = 0; j < m; j++)
obj[p[j].className] = p[j].firstChild.nodeValue;
map_locations[i] = obj;
console.log(obj);
}
答案 1 :(得分:1)
是的,这个问题是因为注释节点,你只需要忽略它们。如果不使用jQuery,最简单的解决方案 - 只需添加对nodeType的检查,并忽略所有而不是1(元素节点):
var map_locations = [], container = document.getElementById('renting-map-js'),
c = container.children, l = c.length, i, obj, p, m, j;
//loop through all child nodes
for ( i = 0; i < l; i++) {
// Ignore non-element nodes.
if(c[i].nodeType != 1)
continue;
obj = {};
//highlights this line
obj.img = c[i].getElementsByTagName('img')[0].src;
p = c[i].getElementsByTagName('p');
m = p.length;
for ( j = 0; j < m; j++)
obj[p[j].className] = p[j].firstChild.nodeValue;
map_locations[i] = obj;
console.log(obj);
}
有关nodeType属性的更多信息 - http://help.dottoro.com/ljkadgoo.php