繁体   English   中英

在事件更改时更新变量jquery

[英]updating a variable jquery on event change

我正在使用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'
                        })
                    };
                };
            })

如您所见,我的问题是,最后运行的状态会覆盖前一个状态,这意味着changeBacktround()函数将更改设置的最新state的背景,即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'
        })
      };

据我了解,如果需要,您需要使用else。 现在,如果状态以0开头,他总是进入第二个条件。否则,如果状态为“ state == 0”或“ state == 1”但不同时进入两个状态

暂无
暂无

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

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