開始學習JavaScript,所以我決定製作一個程序,該程序會接收一個字符串,然後返回相同的字符串,但每個字符的顏色都不相同。Javascript函數未定義
不知道爲什麼當我編譯時,當我打電話給我的彩虹功能時,函數沒有定義。 此外,試圖打印出字符串,但我不知道如果我正確地做。任何合乎邏輯和風格的建議和編輯非常感謝!
<script>
function Rainbow(x) {
var mystring = String(x); @* convert to string*@
var Stringlength = mystring.lenth; @* length fo string *@
var rainbowstring = new Array(Stringlength); @* create array of appropriate size*@
var counter = 0;
var clr, letter;
while (counter < Stringlength) {
letter = mystring.charAt(counter);
var randomnumber = Math.floor(Math.random() * 10); @* random number generator --> 11 means 0-10 *@
switch (randomnumber) {
case 0: clr = #FF0000; break;
case 1: clr = #00FF00; break;
case 2: clr = #0000FF; break;
case 3: clr = #FF00FF; break;
case 4: clr = #000000; break;
case 5: clr = #00FFFF; break;
case 6: clr = #33FFFF; break;
case 7: clr = #33FF00; break;
case 8: clr = #FFFF00; break;
case 9: clr = #FF66CC; break;
}
rainbowstring[counter] = <span style = 'color:"+clr+"'>"+letter+"</span>; @* assign color *@
counter++; @* increment *@
}
return rainbowstring;
}
@* need something that generates colors *@
@* assigns colors to text *@
</script>
<form>
Enter String: <input type ="text" name ="rainbowstring" id ="rainbowinput"/><br>
</form>
<button
type = "button" onclick = "Rainbow(document.getElementById('rainbowinput').value)" > Rainbow Generator
</button>
你應該做的'clr'值的字符串。 –
@ DanielA.White我不知道該怎麼做。你的意思是像'#33FFFF'? – Liondancer
你也犯了一個錯字:'mystring.lenth'應該是'mystring.length'。 – mc10