【问题标题】:jQuery drag and drop, validating draggable idjQuery拖放,验证可拖动id
【发布时间】:2016-02-02 23:49:00
【问题描述】:

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

【问题讨论】:

  • answer 被定义为drop 处理程序的局部变量,它不在validate 函数的范围内。确保 1) 这两个函数共享相同的状态,或 2) validate() 可以自行提取丢弃的答案 ID。此外,即使它有效,您也不会得到任何正确答案,因为您尝试将“正确”与“#正确”进行比较(此处不需要哈希符号)。

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


【解决方案1】:

解决此问题的一种方法是在$(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);
    }
});

【讨论】:

  • 我就知道就是这么简单!!非常感谢你(^__^)你拯救了这一天
猜你喜欢
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
  • 2013-01-27
  • 1970-01-01
相关资源
最近更新 更多