gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:09:51 25 4
gpt4 key购买 nike

出于某种原因,下面的脚本无法使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com