无法在jQuery中获取可拖动div的Id(使用jQuery UI)

1 html javascript php jquery

由于某种原因,下面的脚本无法获取可拖动div的id attr('id'),但它适用于页面上的其他静态元素.我完全困惑为什么这不会工作,如果有人有我的解决方案,我会非常感激.

$(document).ready(function(){
    //$(".draggable").draggable();
    $(".draggable").draggable({ containment: '#container', scroll: false });
    $(".draggable").draggable({ stack: { group: '#container', min: 1 } });


    $("*", document.body).click(function (e) {
        var offset = $(this).offset();// get the offsets of the selected div
        e.stopPropagation();
        var theId = $(this).attr('id');// get the id of the selceted div
        $("#result").text(this.tagName + " id=" + theId + " (" + offset.left + "," + offset.top +")");
        $.post("http://localhost/index.php", "id=" + theId + "&x=" + offset.left + "&y=" + offset.top); //post x,y to php (and the id of the elemnt)
    });

    var req = function () {
        $.ajax({
            url: "out.php",
            cache: false,
            success: function(html){
                $("#stuff").empty().append(html);
                var css_attr = html.split(",");
                $('#1').css('left', css_attr[0] + 'px').css('top', css_attr[1] + 'px');
            },
            complete: function(){
                req();
            }
        });
    };
    req();
});
Run Code Online (Sandbox Code Playgroud)

注意:此脚本依赖于以下JavaScript源.

Nic*_*ver 6

目前,您将点击处理程序附加到DOM中的所有元素*(非常非常糟糕,不要这样做!),包括那些可拖动的子项中的任何子项.

你是正确地阻止事件冒泡使用.stopPropagation(),但它可能是你点击的孩子.draggable,而不是可拖动的本身.你想要的实际上是在监听.draggable元素本身,如下所示:

$(".draggable").click(function (e) {
    var offset = $(this).offset(), 
        theId = this.id;
    e.stopPropagation();
    $("#result").text(this.tagName + " id=" + theId + " (" + offset.left + "," + offset.top +")");
    $.post("http://localhost/index.php", { id: theId, x: offset.left, y: offset.top });
});
Run Code Online (Sandbox Code Playgroud)

这里的其他更改id可以直接访问,通过this.id,并传递对象$.post()是更安全的序列化,就像我上面.

即使上述情况并不完全存在,您可能希望在停止拖动时发送位置,方法是:

$(".draggable").click(function (e) {
Run Code Online (Sandbox Code Playgroud)

对此:

$(".draggable").bind("dragstop", function (e) {
Run Code Online (Sandbox Code Playgroud)

...或更新版本的jQuery(1.4.2+):

$(document.body).delegate(".draggable", "dragstop", function (e) {
Run Code Online (Sandbox Code Playgroud)