问题
Im working on a Jquery project in which the user can drag a 'pill' into a 'cup' and then the amount of pills in the cup can be displayed however ive got a problem with once the pill is in the cup if the user moves the pill it counts it as being dropped again. How do i get the draggable(pill) to be counted once when dropped in the droppable(cup). Is it a case of a for/if loop of storing an array or attaching an identifier to each pill?
here is some of my code html
<div id="PillSpace">
<div class="PillCup"><p>accept: '#Pill'</p></div>
<div class="Pill"><p><img src="resources/capsule.png"/></p></div>
<div class="Pill"><p><img src="resources/capsule.png"/></p></div>
<div class="Pill"><p><img src="resources/capsule.png"/></p></div><br>
<div class="Pill"><p><img src="resources/capsule.png"/></p></div>
<div class="Pill"><p><img src="resources/capsule.png"/></p></div>
<div class="Pill"><p><img src="resources/capsule.png"/></p></div><br>
<div class="Pill"><p><img src="resources/capsule.png"/></p></div>
<div class="Pill"><p><img src="resources/capsule.png"/></p></div>
<div class="Pill"><p><img src="resources/capsule.png"/></p></div>
</div>
the JQuery is:
$(document).ready(function() {
var count = 0;
$( ".Pill").draggable();
$( ".PillCup" ).droppable({
accept: ".Pill",
activeClass: "ui-state-hover",
hoverClass: "ui-state-active",
over:function(){
$( ".PillCup" ).find("p").html(count).text;
},
out:function(){
count--;
$( ".PillCup" ).find("p").html(count).text;
},
drop: function( event, ui ) {
count++;
$( ".PillCup" ).find("p").html(count).text;
}
});
});
Hope someone can help
thanks guys
回答1:
Rather than inc/decrement the count for each drop, try counting the total number of pills in the container:
out: function(){
count = $(".Pill", ".PillCup").count();
$( ".PillCup" ).find("p").html(count).text;
},
drop: function( event, ui ) {
count = $(".Pill", ".PillCup").count();
$( ".PillCup" ).find("p").html(count).text;
}
来源:https://stackoverflow.com/questions/12160017/jquery-drag-and-drop-count-content-of-drop-area