jQuery拖放,验证可拖动的id

时间:2016-02-02 23:49:01

标签: javascript jquery jquery-ui drag-and-drop undefined

我已经构建了一个非常简单的拖放活动。 当在放置区域上删除答案时,其id存储在名为“answer”的变量中。 当点击提交按钮时,它会运行一个名为validate的函数,该函数检查变量答案是否在其中存储了“正确”的id。

问题是,当我点击提交按钮时,它不会运行验证功能,因为它表示“未定义变量答案”。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Yay for drap and drops!</title>
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <style> div {
    height: 100px;
    width: 100px;
    border: solid 2px #000;
    margin: 10px;
    }
  </style>
  <script>
  $(document).ready(function() {
    $("#correct").draggable(); //I have drag capability now!
    $("#wrong").draggable();  //I have drag capability now!
    $("#dropArea1").droppable({
      drop: function(event,ui) {
      var answer = ui.draggable.attr("id");
      console.log(answer);
      }
  });
});  

  </script>
</head>
<body>
<div id="correct">
  <p>CORRECT ANSWER</p>
</div>

<div id="wrong">
  <p>WRONG ANSWER</p>
</div>

<div id="dropArea1">
  <p>I'm the drop area</p>
</div>
<script>
  function validate() {
    if (answer == ("#correct")) {
      window.location.replace("www.google.com") //correct! redirect web page to next activity
    }

    else {
      window.alert("Incorrect, try again") //incorrect, try again
    }
  }
</script>
<button onclick="validate()">Submit</button>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

解决此问题的一个选项是在answer范围之外定义变量$(document).ready(),如下所示:

var answer = null;

$(document).ready(function() {
  $("#correct").draggable(); //I have drag capability now!
  $("#wrong").draggable();  //I have drag capability now!
  $("#dropArea1").droppable({
    drop: function(event,ui) {
    answer = ui.draggable.attr("id");
    console.log(answer);
    }
});