我写了以下代码:http://jsfiddle.net/2YL8Q/5/
var $button = $("button");
var $buttonClicked;
var $instructionText = $("#instructionText");
var $item = $("li");
var $firstItemPicked;
var $secondItemPicked;
var $firstItemIndex;
var $secondItemIndex;
var $clonedItem;
$button.on("click", function () {
$buttonClicked = 1;
$instructionText.html("Instructions: Pick an item");
});
$item.on("click", function () {
if ($buttonClicked === 1) {
$firstItemPicked = $(this);
$firstItemPicked.addClass("selected");
$firstItemIndex = $item.index($(this));
$instructionText.html("Instructions: " + $firstItemPicked.text() + " has been picked, now pick another to swap places with");
$buttonClicked = 0;
alert($firstItemIndex);
} else if ($buttonClicked === 0) {
$clonedItem = $(this).clone();
$secondItemPicked = this;
$($secondItemPicked).after($($clonedItem));
$($firstItemPicked).after($($secondItemPicked));
$($clonedItem).after($($firstItemPicked));
$($firstItemPicked).removeClass();
$($clonedItem).remove();
$buttonClicked = 2;
$secondItemIndex = $item.index($firstItemPicked);
alert($secondItemIndex);
if (($firstItemIndex + 1) <= 4 && ($secondItemIndex + 1) <= 4) {
$instructionText.html("First picked item came from list #1 and ended up in list #1");
}
if (($firstItemIndex + 1) > 4 && ($secondItemIndex + 1) <= 4) {
$instructionText.html("First picked item came from list #2 and ended up in list #1");
}
if (($firstItemIndex + 1) <= 4 && ($secondItemIndex + 1) > 4) {
$instructionText.html("First picked item came from list #1 and ended up in list #2");
}
if (($firstItemIndex + 1) > 4 && ($secondItemIndex + 1) > 4) {
$instructionText.html("First picked item came from list #2 and ended up in list #1");
}
}
});
唯一缺少的是输出第一个拾取的物品来自哪里以及它最终的位置。当我从列表#1中选择第一个项目并使用列表#2中的项目进行交换时,它似乎不起作用。虽然它在我从#2到#1的第一次交换时有效。
我在这里做错了什么帮助?
答案 0 :(得分:1)
因为获取第二个索引时,您将再次获得第一个选定元素的索引。
将您的行更改为
$secondItemIndex = $item.index($secondItemPicked);