JQuery Drag and Drop Count Content of Drop Area?

╄→гoц情女王★ 提交于 2019-12-08 07:53:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!