算数ゲームを作っています。このゲームでは、お子様が引き算記号「-」を 2 つの数字のいずれかにドラッグすると、答えが表示されます (例: 9-4 = 5)。
HTML5 データ属性「data-price」に乱数が表示されています。私が今抱えている唯一の問題は、クラスに「ドロップ」した数値の上に減算記号をドラッグすると、変数「total_costs」に問題の答えが表示されないことです。
(function(){
//declare my variables
var numLow = 1, //lowest number
numHigh = 20,//highest number
$firstNum = $('#firstNum'),
$secondNum = $('#secondNum'),
adjustedHigh, numRand1, numRand2 = null,
total_costs=0;
//Callback function when cancelling the event
function cancel(e){
if(e.preventDefault){
e.preventDefault();
}
return false;
}
//refresh total cost "numbers added"
function refresh_total_costs(total_costs){
$('#total-cost span').text(total_costs);
}
//generates random numbers and stores random numbers in data-price attribute
//and displays random numbers in divs #firstNum and #secondNum
adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
numRand1 = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
numRand2 = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
$firstNum.attr('data-price', numRand1);
$firstNum.text( $("#firstNum").attr("data-price"));
$secondNum.attr('data-price', numRand2);
$secondNum.text( $("#secondNum").attr("data-price"));
refresh_total_costs(total_costs);
//Get the .drop zones
var drop = $('.drop');
var draggedItem = null;
//Add the Event Listener to draggable item "+" symbol
$('.draggable-item').on('dragstart', function(e){
draggedItem = jQuery(this);
}, false);
drop.on('dragover', cancel);
drop.on('dragenter', cancel);
drop.on('drop', function(e){
//Prevent default browser behaviour
e.preventDefault();
//Do the math
total_costs = parseInt($("#firstNum").attr("data-price")) + parseInt($("#secondNum").attr("data-price"));
refresh_total_costs(total_costs);
return false;
});
})();