为什么我为keydown()收到此错误?

时间:2015-09-12 20:31:51

标签: javascript jquery html event-handling

$(document).ready(function(){
  $("#promptButton").click(function(){
    $("#openPrompt").hide();
    startGame();
  });
});

function startGame(){
  $(document).ready(function(){
$("#gameboard").append("<div class='snakeHead' id='head'> hi </div>");
  var direction;
  moveTimer = setInterval(function() {snakeMove()},1000);
  function snakeMove(){
    function snakeDirection(){
      $(".snakeHead").keydown(function(key){
        if (key.which === 38){
            direction = "up";
            return {"margin-top": "-=20px"}
        } else if(key.which === 40){
            direction = "down"
            return {"margin-top": "+=20px"}
        } else if(key.which === 37){
            direction = "left"
            return {"margin-left": "-=20px"}
        } else if(key.which === 39){
            direction = "right"
            return {"margin-left": "+=20px"}
        } else {
            direction = "right"
            return {"margin-left": "+=20px}"
        };
      });
    };
    $('.snakeHead').animate({'margin-left':'+=20px'}, 'slow');
  }
  });
};

我一直在

  

SyntaxError:expect expression,got&#39;)&#39;在第32行第11行。

我的印象是只需要使用在事件触发时调用的函数调用keydown()。我需要另一个表达式来调用吗?

感谢您的帮助,这是我尝试的第一个真正的项目,而且我是自学成才,所以尽量让我尽可能清楚。谢谢!

1 个答案:

答案 0 :(得分:1)

您有语法错误:

function startGame(){
  $(document).ready(function(){
$("#gameboard").append("<div class='snakeHead' id='head'> hi </div>");
  var direction;
  moveTimer = setInterval(function() {snakeMove()},1000);
  function snakeMove(){
    function snakeDirection(){
      $(".snakeHead").keydown(function(key){
        if (key.which === 38){
            direction = "up";
            return {"margin-top": "-=20px"}
        } else if(key.which === 40){
            direction = "down"
            return {"margin-top": "+=20px"}
        } else if(key.which === 37){
            direction = "left"
            return {"margin-left": "-=20px"}
        } else if(key.which === 39){
            direction = "right"
            return {"margin-left": "+=20px"}
        } else {
            direction = "right"
            return {"margin-left": "+=20px}" <--- Here --->
        };
      });
    };
    $('.snakeHead').animate({'margin-left':'+=20px'}, 'slow');
  }
  });
};