0

我有 2 个按钮,当单击任一按钮时,时间如下所示。两个按钮都有单独的输出。我正在尝试使用 clearTimeout,但由于某种原因它没有清除超时。当再次单击按钮时,它只会在已经存在的 ajax 调用之上进行另一个 ajax 调用。如何让 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>
4

1 回答 1

3

您的功能showTime(gotoUrl,output,index)要求showTimeX(gotoUrl, output)成功。

但是showTimeX(gotoUrl,output,index)定义需要索引作为最后一个参数,在调用该函数时没有指定。

难道是索引未定义,所以超时数组不包含任何变量?

于 2016-01-12T01:28:16.943 回答