2016-01-12 160 views
0

我有2個按鈕,當單擊其中任一按鈕時,時間如下所示。兩個按鈕都有獨立的輸出。我試圖使用clearTimeout,但由於某種原因它沒有清除超時。當再次點擊一個按鈕時,它只會在已有的ajax調用之上進行另一個ajax調用。我如何獲得clearTimeout工作?當按鈕再次單擊時,clearTimeout無法按預期工作

<input type = 'submit' value = 'show time' onclick = "showTime('test1.php', 'output1',0)"> 
<div id = 'output1'></div> 

<input type = 'submit' value = 'show time' onclick = "showTime('test1.php', 'output2',1)"> 
<div id = 'output2'></div> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 

<script type = "text/javascript"> 

var timeout = []; 
function showTime(gotoUrl,output,index) { 

if (timeout[index]) { 
clearTimeout(timeout[index]); 
} 

$.ajax({ 
type: "POST", 
url: gotoUrl, 
error: function(xhr,status,error){alert(error);}, 
success:function(data) { 
document.getElementById(output).innerHTML = data; 
showTimeX(gotoUrl, output); 
} //end of success:function(data) 
}); //end of $.ajax 

} //end of function showTime(gotoUrl, output) 

function showTimeX(gotoUrl,output,index) { 

$.ajax({ 
type: "POST", 
url: gotoUrl, 
error: function(xhr,status,error){alert(error);}, 
success:function(data) { 
document.getElementById(output).innerHTML = data; 
timeout[index] = setTimeout(function(){showTimeX(gotoUrl, output, index)}, 5000); 
} //end of success:function(data) 
}); //end of $.ajax 

} //end of function showTime(gotoUrl, output) 

</script> 

回答

3

您的功能showTime(gotoUrl,output,index)調用showTimeX(gotoUrl, output)成功。

showTimeX(gotoUrl,output,index)定義需要索引作爲最後一個參數,當您調用該函數時不會指定它。

難道是索引是未定義的,所以timeout數組不包含任何變量?

+0

我剛剛解決了這個問題,但仍然無法正常工作。 – jessica

+0

你確定'timeout'數組對於$ .ajax裏面的'showTimeX'是可見的嗎?也許嘗試通過它作爲參數之一? – Kamil

+0

啊......有兩個showTimeX,我只爲其中的一個添加了索引! *打額頭* – jessica