我学习javascript,但我遇到了问题。我尝试通过点击按钮将功能结果放入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()的结果答案 0 :(得分:1)
这是一个有效的代码。一些说明:
您使用document
写信document.write()
(这不是一个好习惯)。将变量中的html连接起来然后设置元素div的innerHTML
属性#
你的循环无效。第二个参数是循环的条件,所以你要写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;
}