0
我已經構建了一個非常簡單的拖放操作。 當答案被放置在放置區域時,其ID將存儲在名爲'answer'的變量中。 當提交按鈕被擊中時,它會運行一個名爲validate的函數,該函數檢查變量答案是否在其中存儲了「正確」的ID。jQuery拖放,驗證可拖動的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'處理程序,它不是在「驗證」功能的範圍。確保1)這兩個函數共享相同的狀態,或者2)'validate()'可以自己提取被丟棄的答案ID。此外,即使它起作用,您也不會得到任何正確答案,因爲您試圖將「正確」與「#校正」進行比較(此處不需要使用散列符號)。 – raina77ow