2012-12-04 9 views
2

3 박자를 강조했습니다. 이유는 IE9에서는 작동하지만 IE8에서는 작동하지 않습니다.IE8 'src'속성 값을 가져올 수 없습니다. 개체가 null이거나 정의되지 않았습니다.

SCRIPT5007을 : 내가 IE8에서 실행할 때이 오류가 계속 재산 'SRC'의 값을 가져올 수 없습니다 : 내가 원인 인이 줄을 얻을 디버깅 할 때 객체가 null 또는

정의되지 ->

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

다음은 바이올린 IE6-8에서 http://jsfiddle.net/EgzKv/

답변

3

, .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); 
}​ 
+0

당신은 내 생명의 은인! 영원히 감사하는 친구! – user1467439

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