gpt4 book ai didi

javascript - 使用 jQuery 交换列表项

转载 作者:行者123 更新时间:2023-12-03 12:42:44 25 4
gpt4 key购买 nike

我编写了以下代码: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 时它会起作用。

对我在这里做错的事情有什么帮助吗?

最佳答案

因为在获取第二个索引时,您将再次获取第一个选定元素的索引。

将行更改为

$secondItemIndex = $item.index($secondItemPicked);

它有效:http://jsfiddle.net/2YL8Q/9/

关于javascript - 使用 jQuery 交换列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23479305/

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