2012-05-22 100 views
-1

我想打一個按鈕來啓動的onclick使隨機數保持運行,(使用未捕獲的ReferenceError:spanArray沒有定義

  1. 或2調用),但如果我按它,錯誤消息顯示「未捕獲

的ReferenceError:未定義spanArray」,但上面的數字仍然在運行,我不能

明白的地方是放錯了地方。

PS但是,如果我使用3它正常工作。

Thx!

THX完整的代碼我試圖通過3 http://jsfiddle.net/eVyjC/

function computeRandom(){ 
// skip code: have used loop to create six spans already 
var spanArray = document.getElementsByTagName("span"); 
//1.document.write("<input type = button value = 'start' onclick = \"passKeepMove(value,spanArray) \" name = button1>"); 
//2.document.write("<input type = button value = 'start' onclick = \"setInterval(function(){keepMove(value,spanArray);}, 10) \" name = button1>"); 
//3.setInterval(function(){keepMove(value,spanArray);}, 10) ; 
    } 


function keepMove(val,sp){//call by pointer 

    var index = parseInt(Math.random()*43);//set a increment to avoid repeatition 

    for(i = 0; i < sp.length; i++){ 
    sp[i].innerHTML = val[i+index]; 
    } 
} 


function passKeepMove(v,s){ 
    setInterval(function(){keepMove(v, s);}, 10); 
} 

回答

2

var spanArray前面的var正在spanArray一個局部變量。所以你不能在computeRandom的函數範圍之外訪問它。

你需要使它成爲全局的,或想出一個更好的設計,所以你不需要全局變量。

+0

但爲什麼我使用setInterval(function(){keepMove(value,spanArray);},10)在computeRandom中工作正常嗎? –

+0

因爲我只用它們作爲參數來調用computeRandom中的函數,我認爲它不關係本地或全局? –

+0

我只是一個菜鳥,所以以上只是我的看法。如果它是錯誤的,請告訴我.Thx。 –

相關問題