2011-12-22 110 views
0

我學習的JavaScript和我有問題。我試圖通過點擊按鈕將函數結果放入div。函數導致按鈕按鈕onclick

<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屬性#

  • 您的循環無法正常工作。第二個參數是循環的狀態,所以你ahve寫j <= x.length而不是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 ! – 2011-12-22 11:18:15

+0

Thx,聖誕快樂:) – Modest 2011-12-22 11:23:25