Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在事件更改时更新变量jquery_Javascript_Jquery_Html - Fatal编程技术网

Javascript 在事件更改时更新变量jquery

Javascript 在事件更改时更新变量jquery,javascript,jquery,html,Javascript,Jquery,Html,我正在使用jQuery创建一个交互式体验。我正在努力使我的角色可以进入多个房间 $(document).keydown(function(e) { switch (e.which) { case 39: $("#barry").attr("src", "img/characters/BarryBallRight.png") $("#barry").stop().animate({ left:

我正在使用jQuery创建一个交互式体验。我正在努力使我的角色可以进入多个房间

$(document).keydown(function(e) {
    switch (e.which) {
        case 39:
            $("#barry").attr("src", "img/characters/BarryBallRight.png")
            $("#barry").stop().animate({
                left: 1021
            }, 1250, function() {
                position = $(this).position();
                getCurrentPos(position);
                if (barryPosX > $("#canvas").width()) {
                    if (state == 0) {
                        state = 1
                        changeBackground(state);
                        // reset barry
                        $(this).css({
                            'left': '-100px'
                        });
                        $(this).stop().animate({
                            left: '+=150px'
                        })

                    };
                    if (state == 1) {
                        state = 2;
                        changeBackground(state);
                        // reset barry
                        $(this).css({
                            'left': '-100px'
                        });
                        $(this).stop().animate({
                            left: '+=150px'
                        })
                    };
                };
            })
正如您所看到的,我的问题是运行的最后一个状态覆盖了前一个状态,这意味着
changebacktrond()
函数将更改设置的最新
状态的背景,即
2

我知道我缺少一些逻辑

请注意,
getCurrentPos()
函数仅检索屏幕上当前的
$(“#barry”)
位置。
changeBackground()
函数是一个switch语句,它接受当前状态并相应地更改屏幕背景

提前谢谢

if (state == 0) {
   state = 1
   changeBackground(state);
   // reset barry
   $(this).css({
   'left': '-100px'
   });
  $(this).stop().animate({
  left: '+=150px'
    })

   } else if (state == 1) {
      state = 2;
      changeBackground(state);
      // reset barry
      $(this).css({
       'left': '-100px'
      });
      $(this).stop().animate({
       left: '+=150px'
        })
      };

据我所知,如果需要,您需要使用其他。现在,如果状态从0开始,他总是进入第二个状态。如果它进入'state==0'条件或'state==1'条件,而不是同时进入这两个条件,则使用else

我不敢相信我错过了这个。。。这是我漫长的一天。我也喜欢你的解释!