jQuery 拖放,验证可拖动 ID

jQuery drag and drop, validating draggable id

本文关键字:拖动 ID 验证 拖放 jQuery      更新时间:2023-09-26

我构建了一个非常简单的拖放活动。当答案被放在放置区域时,其 id 存储在名为"答案"的变量中。当点击提交按钮时,它会运行一个名为 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>
解决此问题

的一种选择是在$(document).ready()范围之外定义变量answer,如下所示:

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