2014-01-19 56 views
2

我正在嘗試創建2個按鈕,1以啓動腳本,1以停止它。爲javascript創建按鈕

var timerID = setInterval(function() { 
    $.ajax({ 
     url: "script.php", 
     context: document.body 
    }); 
    }, 60 * 1000); 


    clearInterval(timerID); 

我不知道我怎麼會得叫這個,這是我試圖:

<button id="id" onClick="timerID();"></button> 
+0

正如其名稱所暗示已經'timerID'是一個ID(數值),而不是一個功能。你不能稱它。查看http://eloquentjavascript.net/chapter3.html以瞭解更多有關功能的信息。 –

回答

0

你會希望把它包起來另一個函數內部:

var timerID; 
var myTimerFn = function() { 
    timerID = setInterval(function() { 
     $.ajax({ 
      url: "script.php", 
      context: document.body 
     }); 
    }, 60 * 1000); 
}; 

// call 
myTimerFn(); 

然後關閉它的另一個函數。或者傳遞一個參數來告訴它是否開始或停止。

0

我想你想啓動和停止計時器?

var timerID ; 

function start() 
{ 
    var timerID = setInterval(function() { 
     $.ajax({ 
      url: "script.php", 
      context: document.body 
     }); 
    }, 60 * 1000); 
} 

function stop() 
{ 
    clearTimeout(timerID); 
} 

這是你會怎麼稱呼它:

<button id="start" onClick="start();"></button> 
<button id="stop" onClick="stop();"></button> 

更多有關setInterval檢查這裏:http://www.w3schools.com/js/js_timing.asp

+0

不知何故,這仍然無法正常工作。代碼現在看起來更好,但按下按鈕後,我不會重定向到任何位置 – user3170212

+0

'$ .ajax'不會重定向,它會從url中返回響應。您必須在腳本中處理該響應。我會建議擴大你的問題,以便我們瞭解你試圖實現的目標 – andrew

+1

我建議不要共享鏈接到w3schools.com - http://www.w3fools.com/ – andrew