我一直在爲此奮鬥一段時間。我想創建的是根據用戶的輸入輸出一個星號三角形。讓我們說,用戶輸入的大小爲5,這將是這個樣子:在JavaScript中創建星號掙扎
*
**
***
****
*****
我的HTML看起來像:
<p>
Size: <input type="text" id="size">
<input type="button" value="Draw" onclick="draw()">
</p>
<pre id="output">
</pre>
在我的JavaScript,我有:
function draw()
{
var size = customJS.get ("size"); //I have a custom library where it get the Id from HTML
var theTriangle = makeTriangle(size.value); //sending in the size
customJS.set ("output", theTriangle); //will set theTriangle to display to "output" in HTML
}
function makeTriangle(theSize)
{
var allLines = ""; // an empty string to hold the entire triangle
for (var i = 0; i <= size; i++) // this loop size times
{
var oneLine = createLine (i <= size); // amount of asterisks for this line
allLines += oneLine;
}
return allLines;
}
function createLine (length)
{
var aLine = ""; // an empty string to hold the contents of this one line
for (var j = 0; j <= i; j++) //this loop length times
{
aLine += '*';
}
return aLine + "<br>";
}
任何人有任何提示我如何解決這個問題?非常感謝!
所以我已經改成'var oneLine = createLine(i);'b ut當我點擊'Draw'時什麼都沒有發生# – 2013-03-03 21:22:42
我相信'customJS.set'在這個函數中不是問題,因爲我已經將它用於其他javascript,並且它工作正常。問題必須在'makeTriangle'或'createLine'函數中,但我似乎無法弄清楚... – 2013-03-03 21:27:51
@KennyWong:我剛剛看到一件事(你分配'size'的方式)我已經添加到我的答案。 – icktoofay 2013-03-03 21:28:17