繁体   English   中英

jQuery / JS-变量似乎未更新?

[英]jQuery/JS - Variable doesn't seem to be updated?

我希望用户单击DIV元素,并将其添加到JavaScript中的变量中,然后在该变量的值更改时发生不同的事情。 当我第一次单击div元素时,它显示“您在这里!”。 但是当我第二次单击div元素时……似乎什么都没有发生。 似乎该变量没有被更新。

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;
        });
    };
});

您需要检查点击处理程序中的条件

$(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++;
    });
});

请以下面的方式编写您的代码,希望对您有所帮助

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;
  });
});

在事件处理程序中测试$ test变量,并且在文档就绪事件中仅需要一个事件处理程序附加。 顺便说一下,文档准备功能仅运行一次。

错误是:您正在为$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;
         }
    });
});

小提琴

只是我的版本:

$(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++

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM