2011-12-22 7 views
0

자바 스크립트를 배웠고 문제가 있습니다. 버튼을 클릭하여 함수 결과를 div에 넣으려고합니다. 버튼으로 div에 함수 결과를 입력하십시오.

<script type="text/javascript"> 

function choinka() { 

var x=document.getElementById("liczba").value; 
var a="W"; 
var b="W"; 
var px="15" 

for(j=1;j<=x;j++) 
{ 
for(i=j;i<=x;i++) 
{ 
document.write("<span style='color:white;line-height:" + px + "px;'>" + a + "</span>"); 
} 
document.write("<span style='color:green;background:green;line-height:" + px + "px;'>" + b + "</span>"); 
b+="WW"; 
for(k=j;k<=x;k++) 
{ 
document.write("<span style='color:white;line-height:" + px + "px;'>" + a + "</span>"); 
} 
document.write("<br />"); 
} 
for(k=1;k<=x/2;k++) 
{ 
for(m=1;m<=x;m++) 
{ 
document.write("<span style='color:white;line-height:" + px + "px;'>" + a + "</span>"); 
} 
b="W"; 
document.write("<span style='color:brown;background:brown;line-height:" + px + "px;'>" + b + "</span>"); 

for(m=1;m<=x;m++) 
{ 
document.write("<span style='color:white;line-height:" + px + "px;'>" + a + "</span>"); 
} 
document.write("<br />"); 
} 

} 

</script> 

과 몸

가 포함되어

<p>Wielkość: <input type="text" id="liczba" /><input type="submit" value="Rysuj" onclick="choinka()" /></p> 

<div id="choinka"></div> 

어떻게 DIV 번호의 choinka로 버튼을 클릭하여 기능 choinka()의 결과를 넣어?

답변

1

다음은 작동 코드입니다. 일부 노트 :

  • 작성중인 document-document.write()를 사용하여 (좋은 습관이 아니다). 변수에서 html을 연결 한 다음 요소 div의 innerHTML 속성을 설정하는 것이 더 효율적입니다. #

  • 루프가 작동하지 않습니다. 당신이 j <= x.length를 작성 ahve 그래서 두 번째 매개 변수는 루프의 조건없는 j <= x

여기

jsfiddle (;-) 메리 크리스마스)


function choinka() { 

    var x = document.getElementById("liczba").value; 
    var a = "W"; 
    var b = "W"; 
    var px = "15"; 

    var html = ''; 

    for (j = 1; j <= x.length; j++) { 
     for (i = j; i <= x.length; i++) { 
      html += "<span style='color:white;line-height:" + px + "px;'>" + a + "</span>"; 
     } 
     html += "<span style='color:green;background:green;line-height:" + px + "px;'>" + b + "</span>" 
     b += "WW"; 
     for (k = j; k <= x.length; k++) { 
      html += "<span style='color:white;line-height:" + px + "px;'>" + a + "</span>"; 
     } 
     html += "<br />"; 
    } 
    for (k = 1; k <= x.length/2; k++) { 
     for (m = 1; m <= x.length; m++) { 
      html += "<span style='color:white;line-height:" + px + "px;'>" + a + "</span>"; 
     } 
     b = "W"; 
     html += "<span style='color:brown;background:brown;line-height:" + px + "px;'>" + b + "</span>"; 

     for (m = 1; m <= x.length; m++) { 
      html += "<span style='color:white;line-height:" + px + "px;'>" + a + "</span>"; 
     } 
     html += "<br />"; 
    } 

    document.getElementById('choinka').innerHTML = html; 

} 
+0

멋진 디디에에 동작하는 예제입니다 G! –

+0

Thx, 메리 크리스마스 :) – Modest

관련 문제