var のスコープは、value
その関数内の他のすべての関数からアクセスできますdocument ready
(あなたの場合は (それがある場合は、それ以外の場合は完全にグローバルな var 名です))。別の方法は、あなたをObject**
に定義することです。これにより、すべての外部および他の関数に対してもグローバルになりますvar
window
「通常の」方法といくつかの即時呼び出し関数式を使用した例で、違いを明確に確認してください。
var text = "Hello!"; // Global
(function sayhello(){
alert(text); // Ok, works
})();
http://jsbin.com/apuker/2/edit
(function defineVar(){
var text = "Hello!"; // Private
})();
(function sayhello(){
alert(text); // No dice
})();
http://jsbin.com/apuker/4/edit
(function defineVar(){
window.text = "Hello!";
})();
(function sayhello(){
alert(text); // Watta?... IT WORKS!
})();
そしてところで、あなたのコードは次のようになるはずです:(とより良いことに注意してください)#reset
if (timer) return;
var timer = null,
interval = 1000,
value = 48;
$("#start").click(function() {
if (timer) return; // return - if timer is not null (true).
timer = setInterval(function () {
value++;
$("#input").val(value);
}, interval);
});
$("#reset").click(function() {
value = 0;
});
$("#stop").click(function() {
clearInterval(timer);
timer=null;
});