2012-12-04 93 views
2

這一直強調了我3個晚上現在......我不知道它爲什麼在IE9中工作,但不是IE8。我不斷收到這個錯誤,當我在IE8的運行:IE8無法獲取屬性'src'的值:對象爲空或未定義

SCRIPT5007:無法獲得屬性「src」中的值:對象爲空或未定義

當我嘗試調試,我得到這條線是原因 - >

 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); 
     } 

這裏是小提琴http://jsfiddle.net/EgzKv/

回答

3

在IE6-8,。兒童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); 
}​ 
+0

你剛纔救了我的命!永遠感激的伴侶! – user1467439

1

是的,因爲註釋節點的這個問題,你只需要忽略它們。最簡單的辦法,如果你不使用jQuery - 只需添加檢查節點類型,並忽略所有,而不是1(Element節點):

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

相關問題