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

标签 php javascript jquery html

出于某种原因,下面的脚本无法使用 attr('id') 获取可拖动 div 的 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();
});

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

最佳答案

目前,您使用 * 将点击处理程序附加到 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 });
});

此处的其他更改是id 可以通过this.id 直接访问, 并将对象传递给 $.post()序列化更安全,就像我在上面所做的那样。

虽然上面的内容还不是完全,但您可能希望在停止拖动时发送位置,方法是更改​​此:

$(".draggable").click(function (e) {

对此:

$(".draggable").bind("dragstop", function (e) {

...或在较新版本的 jQuery (1.4.2+) 中:

$(document.body).delegate(".draggable", "dragstop", function (e) {

关于php - 无法在 jQuery 中获取可拖动 div 的 ID(使用 jQuery UI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/740644/

相关文章:

javascript - 如何随机化这种两个不同的javascript数组

jquery - 如何将日期选择器最大日期限制为今天?

php从公司名称获取谷歌地点详细信息

php - 插入值时 mysqli_real_escape 看起来不正确

javascript - 每当我导航到不同的 Vue.js 路线时,我都会被发送到我导航到的 View 的底部,我无法弄清楚为什么

php - 在同一页面内将 javascript 变量值发送到 php

php - cakePhp 3 连接两个不相关的 mysql 表(松散相关)

php - PHP 中的多线程

javascript - 使用 jQuery 将值从文本框提供给变量

JQuery - 删除调整大小功能