2014-01-08 50 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++