2011-07-17 5 views
0

이 패턴에 대한 많은 게시물을 보았지만 여전히 광산 코드에서 작동하지 않는 이유를 이해하지 못했습니다. 우분투 10.04에서 Chromium 사용하기.innerHTML 대체 패턴이 작동하지 않습니다.

function showDescription(){ 
    var description = document.createElement('div'), 
    eventTarget = window.event.target, 
    newHTML = description.innerHTML; 

    description.id = 'description'; 

    switch(eventTarget.getAttribute('data-par')){ 
     case 'links': newHTML = newHTML.replace(newHTML, 'links') 
      break; 
     case 'images': newHTML = newHTML.replace(newHTML, 'images') 
      break; 
    }; 
    console.log(newHTML); 
    parentElement.insertBefore(description, parentElement.firstChild.nextSibling); 
}; 

    var descParLi = descPars.getElementsByTagName('li'); 
    for (var i = 0; i < descParLi.length; i++){ 
    descParLi[i].addEventListener("click", showDescription); 
}; 

이 코드는 다른 기능에 포함되어 있습니다. 이상하게도, 콘솔에서 newHTML의 가치를 알지만, html에는 아무런 변화가 없다는 것이 문제입니다. 뭐가 잘못 되었 니? 어떻게 고치는 지?

+0

'window.event'는 인터넷 익스플로러에서만 유효합니다. "addEventListener()"를 추가하면 이벤트 객체가 함수의 첫 번째 매개 변수로 전달됩니다 (흥미롭게도 Internet Explorer에서 ** 작동하지 않음). – Pointy

+0

약간의 바이올린을 만들 수 있습니까? – ChristopheCVB

+2

@Pointy : 이상하게도 (전날 배웠던) Chrome은 핸들러에 대한 인수 외에도'event'를'window'의 속성으로 만들어 이러한 점에서 IE를 모방합니다. http://jsfiddle.net/SdMX9/ – user113716

답변

2

작성한 실제 div에 컨텐츠를 추가하지 않습니다.

newHTML = description.innerHTML 

... 나 : 어떤 일에 지점이 없습니다

switch(eventTarget.getAttribute('data-par')){ 
    case 'links': description.innerHTML = 'links' 
     break; 
    case 'images': description.innerHTML = 'images' 
     break; 
}; 

console.log(description.innerHTML); 

newHTML.replace(newHTML, 'images') 

이 ... description는 새로운 요소이기 때문에 어떤 innerHTML을이 없기 때문에 콘텐츠가 아직 없습니다.


편집 : 나는 위의 변수 이름 div 대신 description을 사용. 대신 description를 사용해야합니다

description.innerHTML = 'xxxxx' 

를 수정했습니다.

여기에 전체 기능입니다 :

var i = 0; 

function showDescription(){ 
    var description = document.createElement('div'), 
    eventTarget = window.event.target; 

    description.id = 'description' + i; // <-- make the ID unique 

    i++; // <-- increment "i" so that it's different on the next run 

    switch(eventTarget.getAttribute('data-par')){ 
     case 'links': description.innerHTML = 'links' 
      break; 
     case 'images': description.innerHTML = 'images' 
      break; 
    }; 
    console.log(description.innerHTML); 

     // v----What is parentElement supposed to reference? 
    parentElement.insertBefore(description, parentElement.firstChild.nextSibling); 
} 

공지 사항은 내가 당신의 ID마다 고유합니다 그래서 i를 증가했다.

다른 요소가 표시되기 전에 요소를 제거하는 경우에는 필요하지 않습니다.

또한 parentElement이 있습니다. 나는 그것이 무엇을 참조해야하는지 모른다. 그것은 어떤 적절한 변수가 표시되지 않는 경우

, 당신은 괜찮아요,하지만이 target의 부모에 대한 참조 할 필요가있는 경우에, 당신은 대신이 작업을 수행해야합니다

target.parentNode.insertBefore(description, target.parentNode.firstChild.nextSibling); 
+0

종합적인 답변 주셔서 감사합니다. – I159

+0

@ I159 : 오신 것을 환영합니다. – user113716

0

그것은 당신을 보인다 실제로 newHTML을 innerHTML의 가치로 만들지 않았습니다.

description.innerHTML = newHTML; 
관련 문제