2014-01-08 84 views
0

我想要用戶點擊一個DIV元素,並讓它在JavaScript中爲變量加1,並且隨着該變量值的變化發生不同的事情。當我第一次點擊div元素時,它會顯示「你在這裏!」但是當我第二次點擊div元素時......沒有任何事情發生。看起來這個變量沒有被更新。jQuery/JS - 變量似乎沒有更新?

var $test = 0; 
$(document).ready(function() { 

if ($test == 0) { 
    $("#textbox").click(function() { 
     $(textbox).text("You and here!"); 
     $test = $test + 1; 
     }); 
    }; 

if ($test == 1) { 
    $("#textbox").click(function() { 
     $(textbox).text("Now, you are there!"); 
     $test = $test + 1; 
     }); 
    }; 
}); 

回答

3

您需要檢查條件的點擊處理程序中

$(document).ready(function() { 
    //declare it as a closure variable instead of addint it to the global scope 
    var test = 0; 
    $("#textbox").click(function() { 
     //check the value of test here 
     if (test == 0) { 
      $(textbox).text("You and here!"); 
     } else if (test == 1) { //or just else 
      $(textbox).text("Now, you are there!"); 
     } 
     //increment the value of test 
     test++; 
    }); 
}); 
+0

只是別人只.... –

+0

咖啡@當測試成爲2時,C鏈接不知道OP想要什麼或更多:( –

+1

可能是他''測試=測試 - 1;'''case test == 1'' – zzlalani

1

以下方式請寫出你的代碼希望這將有所幫助

var $test = 0; 
$(document).ready(function() { 

    $("#textbox").click(function() { 

    if ($test == 0) { 
     $(textbox).text("You and here!"); 
    }; 

    if ($test == 1) { 
     $(textbox).text("Now, you are there!"); 
    }; 

    $test = $test + 1; 
    }); 
}); 
0

測試日$測試變量的內事件處理程序和只有一個事件處理程序附加是必需的文檔準備事件。 順便說一下,文件準備就緒功能只運行一次。

0

錯誤在於:您正在爲每個$test變量值註冊一個新的事件處理程序。相反,試試這個:

var $test = 0; 
$(document).ready(function() { 
    $("#textbox").click(function() { 
     switch($test) { 
      case 0: 
       $(this).val("You and here!"); 
       $test = $test + 1; 
      break; 
      case 1: 
       $(this).val("Now, you are there!"); 
       $test = $test + 1; 
      break; 
     } 
    }); 
}); 

Fiddle

+0

-1,你沒有'$ test ++' – Fresheyeball

+0

我不明白 - 請解釋或恢復downvote。 – RaviH

+0

你確定嗎?看小提琴http://jsfiddle.net/y54Mb/。 $ test ++可以做哪些$ test = $ test + 1的魔法? – RaviH

0

只是我的版本:

$(document).ready(function() { 
    var test  = 0, 
     $textBox = $('#textbox'); 
    $textbox.on('click', function() { 
     var message; 
     if (test == 0) { message = "You and here!"; } 
     if (test == 1) { message = "Now, you are there!"; } 
     if (message) { $textbox.text(message); } 
     test++; 
    }); 
}); 

只是爲了好玩

$ -> 
    test  = 0 
    $textBox = $ '#textbox' 
    $textBox.on 'click', -> 
    message = switch test 
     when 0 then "You and here!" 
     when 1 then "Now, you are there!" 
    $textbox.text message if message 
    test++