我用一些测试用例做了一张图片,只是为了告诉你计算什么时候出错。在第 3 种情况下,如果我移出第 1 项而不是第 2 项,它会起作用。在尝试解决这个问题几个小时后,我开始感到有点盲目。
计算有什么问题,可能是事件吗?有没有更好的方法来做到这一点?
jsbin:http: //jsbin.com/ejasun/1/edit
代码:
var price = 0, math = '', items = [], state = 'outside';
$(function() {
function calcPrice(math) {
var value = null;
if(items.length === 0) {
price = 0;
}
console.log("Item array: " + items);
$.each( items, function( key, value ) {
if(math == 'add')
price += $(".draggable[data-item='" + value + "']").data('price');
console.log("Total price: " + price);
if(math == 'remove'){
console.log("Total price " + price + " -= " + $(".draggable[data-item='" + value + "']").data('price'));
price -= $(".draggable[data-item='" + value + "']").data('price');
}
});
$("#droppable").text(price);
}
$(".draggable").draggable({ containment: "#container", scroll: false });
$("#droppable").droppable({
drop: function(e, u) { items.push(u.draggable.data('item'));
price = 0;
calcPrice('add');
u.draggable.data('state', 'inside');
},
out: function(e, u) {
if(u.draggable.data('state') == 'inside') {
u.draggable.data('state', 'outside');
items.splice($.inArray(u.draggable.data('item'), items,1));
calcPrice('remove');
}
}
});
});
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="container">
<div id="droppable"></div>
<div class="draggable" data-item="2" data-price="542" data-state="outside">item: 2<br>price: 542</div>
<div class="draggable" data-item="1" data-price="541" data-state="outside">item: 1<br>price: 541</div>
</div>
</body>
</html>