开发者

JQuery - Drag & Drop - Id draggable element

I'm new in this forum

I learned j开发者_JAVA百科query from 2 week and i'm fairly inexperienced. My site is build with asp.net mvc and use jquery 1.4.1

this is the code

html

...

<% foreach (var item in Model.Amici)
    {%> 
    <div id="amico_<%= item.Id %>" idAmico="<%= item.Id %>">
    <%= item.Name %>
    </div> 
    <% } %>

....

script


    
    $(function() {
        $("div[id^='amico_']").draggable({ revert: "valid" });
        $("#droppable").droppable({
            activeClass: "ui-state-hover",
            hoverClass: "ui-state-active",
            drop: function(event, ui) {
                var index = $(".ui-draggable").attr('idAmico');
                $(this)
                   .addClass("ui-state-highlight")
                   .find("p")
                   .html("id = " + index);
            }
        });
    });

the problem is that id attribute's value is always 1 (index variable) while are 1 and 2. (red row) where am i wrong?

thanks so much for your replies Alberto


Here is one quick note that may help.

<% foreach (var item in Model.Amici)
{%> 
<div id="amico_" idAmico="">
    <%= item.Name %>
</div> 
<% } %>

In this example, and based on your jQuery selector, I think you are expecing the id of each div to be "amico_1", "amico_2" and so on... perhaps based on the item id? In any case, the id attribute must be unique.

<% foreach (var item in Model.Amici)
{%> 
<div id="amico_<%= item.Id %>" idAmico="" class="drag">
    <%= item.Name %>
</div> 
<% } %>

Notice also that I have added a class of "drag" to the div.

This means your selector can be updated from this:

$("div[id^='amico_']").draggable({ revert: "valid" });

To this

$(".drag").draggable({ revert: "valid" });

And my last suggestion is that you've got a small mistake on this line...

var index = $(".ui-draggable").attr('idAmico');

It should actuall be

var index = $(ui.draggable).attr('idAmico');

You should notice that there is a parameter named ui that gets passed into your droppable event. This contains the current dragged element.

Hope this helps.


It's because in your drop function, you are arbitrarily pulling $(".ui-draggable") which is any class on the page that matches this, not the child object of the object being dropped.

From the docs I found (http://jqueryui.com/demos/droppable/#event-drop) you can access the element that was dropped with ui.draggable

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜