2014-11-11 4 views
0

나는 계산기 응용 프로그램에서 일하고 있습니다. 현재 함수를 div에 푸시하여 다음과 같이 표시하려면 다음 함수를 작성하십시오.자바 스크립트 반환 개체 htmlelement

function addtoScreen(vTag){ 

     var screen = document.getElementById("screen"); 

     if(currentFunction.length == 1){ 

     var newCalc = document.createElement("p");  
     newCalc.setAttribute("class", "calc"); 

     var opInt = "<span>"+vTag+"</span>"; 

     newCalc.innerHTML = opInt; 
     screen.innerHTML = newCalc; 

     }else{ 
     var opInt = "<span>"+vTag+"</span>"; 
     newCalc = document.getElementById("screen").lastElementChild; 
     newCalc.innerHTML = opInt; 

     } 
    } 

if 부분은 [object HTMLParagraphElement]를 계속해서 잘못 표시합니다. .value를 사용하려고 시도했지만 객체가 value 속성이없는 전체 요소이므로 null 만 반환합니다.

편집 : vTag는 배열로 전달되는 함수에서 전달되는 문자열이라는 것을 언급하지 않았습니다.

function addtoScreen(vTag){ 

    var screen = document.getElementById("screen"); 

    if(currentFunction.length == 1){ 

    var newCalc = document.createElement("p");  
    //newCalc.setAttribute("class", "calc"); 
    newCalc.className = "calc"; 

    //var opInt = "<span>"+vTag+"</span>"; 
    var opInt = document.createElement("span"); 
    opInt.innerHTML = vTag; 

    //newCalc.innerHTML = opInt; 
    newCalc.appendChild(opInt); 

    //screen.innerHTML = newCalc; 
    screen.appendChild(newCalc); 

    }else{ 
    //var opInt = "<span>"+vTag+"</span>"; 
    var opInt = document.createElement("span"); 
    opInt.innerHTML = vTag; 

    newCalc = screen.lastChild; 

    //newCalc.innerHTML = opInt; 
     if(newCalc) 
     { 
    newCalc.appendChild(opInt); 
     } 
     else 
     { 
     screen.appendChild(opInt); 
     } 

    } 

}

+1

선택적으로 조각으로, 당신의 HTML을 추가하시기 바랍니다 : 이런 식으로 뭔가에 대해 (내가 이전의 코드를 주석) 어떻게 – ps2goat

+1

'vTag '는 DOM 요소입니까? 당신은 그것의 내용을 얻기 위해'vTag.outerHTML'을 사용할 수 있어야합니다. –

+1

길이를'currentFunction.length == 1 '과 비교하는 대신'currentFunction.length = 1'을 설정하는 것처럼 보입니다. –

답변

2

.
+0

그 덕분에, 고마워요. 왜 appendChild가 작동하고 innerHTML이 작동 했습니까? innerHTML은 문자열을 할당하는 데에만 사용되며 appendChild는 DOM을 실제로 수정하기 위해 사용됩니까? –

+0

그런 식으로 좀 더 자세한 정보가있는 링크가 있습니다 : [링크] (http://stackoverflow.com/questions/16126960/what-is-the-difference-between-appendchild-insertadjacenthtml-and -innerhtml) –