0

我正在(和我的一位学生一起工作)使用 jqueryui 获取被删除对象的属性。被丢弃的对象是图像。通过对可拖动的单个 jquery 调用将所有图像设置为可拖动。

这里的挑战实际上是获取被放置在放置目标上的对象的任何属性。drop 事件处理程序工作正常(我可以很容易地提醒它) - 但无法获得被删除对象的任何属性。

此代码也可在http://jsfiddle.net/reaglin/FUvT8/4/获得

注意 - 真正的动作发生在

(1) 调用draggable() 使对象可拖放 (2) 创建图像并将其添加到文档正文 (3) 调用handleDropEvent。

这是处理扑克牌的一个很好的例子——但这个例子使用了 Dr. Who 角色。

$ (init);

function image(id, image1) {
this.id = id;
this.image1 = image1;
}

$('#deal').click(function () {dealAll(
    dealCard(randomCard()));
});

$(function() {
 $( "#draggable" ).draggable({ containment: "#left"});
  });

function init() {
  $('.drop').droppable( {
    drop: handleDropEvent
 } ); 
 $("img").draggable();
}
// global variables
var cardsInDeck = new Array();
var numberOfCardsInDeck = 15;
cardsInDeck[0] = "Ace";
cardsInDeck[1] = "Grace";
cardsInDeck[2] = "Susan";
cardsInDeck[3] = "Ian";
cardsInDeck[4] = "Barbara";
cardsInDeck[5] = "Brigadier";
cardsInDeck[6] = "Romana I";
cardsInDeck[7] = "K9";
cardsInDeck[8] = "Tegan";
cardsInDeck[9] = "Jamie";
cardsInDeck[10] = "Sarah Jane";
cardsInDeck[11] = "Jo";
cardsInDeck[12] = "Romana II";
cardsInDeck[13] = "Yates";
cardsInDeck[14] = "Leela";

var cardsDealt = new Array();
// deal 5 cards at once - works
function dealAll(){
var z=0;
for (z=0;z<5;z++) {
   cardsDealt[z] = new Image(z,dealCard(randomCard()));
}
}

//deal cards - works
function dealCard(i) {
if (numberOfCardsInDeck == 0) return false;
var $img = new Image();
    $img.src = "http://debsiepalmer.com/images/companions/" + cardsInDeck[i] + ".jpg";
// Here I set the ID of the object
$img.id=cardsInDeck[i];
$img.class='drag';

$("img").draggable();
     document.body.appendChild($img);
removeCard(i);
return $img;
}
// deal randomly - works
function randomCard() {
return Math.floor(Math.random() * numberOfCardsInDeck);   
}
// remove spent cards from pool -works
function removeCard(c)
{

for (j=c; j <= numberOfCardsInDeck - 2; j++)
{
    cardsInDeck[j] = cardsInDeck[j+1];
}
numberOfCardsInDeck--;
numberOfCardsInDeck--;
numberOfCardsInDeck--;
}

// this is what to do when card drops in tardis
function handleDropEvent( event, ui ) {
 // Here I want the id of the dropped object
}
4

1 回答 1

0

对 jqueryui 的文档进行更多研究 - 提供这些答案;

首先,当图像被声明为可拖动时 - 这需要在添加到 document.body 之后完成 - 这是因为 jquery 选择器使用 DOM 来创建对象列表 - 所以行

$("img").draggable();
document.body.appendChild($img);

将更改为

document.body.appendChild($img);
$("img").draggable();

同样在此示例中,所有图像都被声明为可拖动的,但是我们可以更具体地使附加到文档的图像可拖动。

document.body.appendChild($img);
$('#'+$img.id).draggable();

一旦图像可拖动 - 传递给 handleDropEvent 的对象的属性是 event 和 ui - ui 对象的可拖动属性是一个 jquery 对象,它可以访问它包含的对象的属性;

function handleDropEvent( event, ui ) {
  alert(ui.draggable.attr("id"));
}
于 2013-11-05T15:15:27.183 回答