jQuery Draggable only allowing 1 image to be draggable

送分小仙女□ 提交于 2019-12-08 03:56:54

问题


I have a page full of images, album artwork to be precise. I have added code to make it draggable and it will only allow me to drag the first image on the page.

Why is this?

 $(document).ready(function () {
            $("#draggable").each(function () {
                $(this).draggable({
                    revert: function (dropped) {
                        var dropped = dropped && dropped[0].id == "droppable";
                        if (!dropped);
                        return !dropped;
                    }
                });
            });

            $("#droppable").droppable({
                drop: function (event, ui) {
                    var AlbumToAdd = ui.draggable.data("id");
                    if (AlbumToAdd != '') {
                        // Perform the ajax post
                        $.post("/ShoppingCart/DragToCart", { "id": AlbumToAdd },
                            function (data) {
                                // Successful requests get here
                                // Update the page elements
                                $('#cart-total').text(data.CartTotal);
                            });
                    }
                }
            });

        });

Comment if you need to see more code


回答1:


Usually id's are supposed to be unique. So doing $("#draggable").each... is usually not a good practise. Changing this into a class selector should solve the issue.

So transform it into:

$(".draggable").each(function () { ...

And your html into

<div class="draggable" class="ui-widget-content">
    <p>Drag me around</p>
</div>

You can see my working example (simplified) here.



来源:https://stackoverflow.com/questions/7203519/jquery-draggable-only-allowing-1-image-to-be-draggable

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