简体   繁体   English

jQuery拖放,验证可拖动的id

[英]jQuery drag and drop, validating draggable id

I've built a really simple drag and drop activity. 我建立了一个非常简单的拖放活动。 When an answer is dropped on the drop area, its id is stored in a variable called 'answer'. 当答案放在放置区域时,其ID将存储在名为“答案”的变量中。 When the submit button is hit it runs a function called validate which checks if the variable answer has an id of 'correct' stored inside of it. 按下提交按钮后,它将运行一个称为validate的函数,该函数检查变量答案中是否存储有“正确”的ID。

The problem is, when I hit the submit button it doesn't run the validate function because it says 'the variable answer is not defined'. 问题是,当我按下“提交”按钮时,它没有运行验证功能,因为它说“未定义变量答案”。

<!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>

One option to fix this is to define the variable answer outside of the $(document).ready() scope, like this: 解决此问题的一种方法是在$(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);
    }
});

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

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