我有一个带有向上和向下按钮的值列表。如果我想单击向上按钮,则元素会以列表中的先前值向上移动,然后单击向下按钮,它们会向下移动到列表中的下一项。我的示例代码在这里,
<ul>
<li> 1 <button class="up">UP</button> <button class="down">DOWN</button></li>
<li> 2 <button class="up">UP</button> <button class="down">DOWN</button></li>
<li> 3 <button class="up">UP</button> <button class="down">DOWN</button></li>
<li> 4 <button class="up">UP</button> <button class="down">DOWN</button></li>
<li> 5 <button class="up">UP</button> <button class="down">DOWN</button></li>
</ul>
<script type="text/javascript">
function moveUp(element) {
if(element.previousElementSibling)
element.parentNode.insertBefore(element, element.previousElementSibling);
}
function moveDown(element) {
if(element.nextElementSibling)
element.parentNode.insertBefore(element.nextElementSibling, element);
}
document.querySelector('ul').addEventListener('click', function(e) {
if(e.target.className === 'down') moveDown(e.target.parentNode);
else if(e.target.className === 'up') moveUp(e.target.parentNode);
});
</script>
这是带有要显示的值列表的代码,但我希望以这种格式显示数组值,该格式根据索引执行向上和向下功能。 我的数组元素是:
[
{ id: "Racer-101", rank: "1"},
{ id: "Racer-102", rank: "2"},
{ id: "Racer-103", rank: "3"},
{ id: "Racer-104", rank: "4"},
{ id: "Racer-105", rank: "5"},
{ id: "Racer-106", rank: "6"},
{ id: "Racer-107", rank: "7"},
{ id: "Racer-108", rank: "8"},
{ id: "Racer-109", rank: "9"}
]
数组值怎么可能..
最佳答案
如果您想对数组
执行相同的操作,您所需要做的就是检查给定的元素
是否有前一个
> 或 next
元素,以便您可以交换两个对象以避免索引越界
。
这就是您的代码:
function moveUp(id) {
let index = arr.findIndex(e => e.id == id);
if (index > 0) {
let el = arr[index];
arr[index] = arr[index - 1];
arr[index - 1] = el;
}
}
要在数组
中向上移动元素
,您需要确保此元素
不是数组中的第一个元素,则执行交换操作。
function moveDown(id) {
let index = arr.findIndex(e => e.id == id);
if (index !== -1 && index < arr.length - 1) {
let el = arr[index];
arr[index] = arr[index + 1];
arr[index + 1] = el;
}
}
要向下移动元素
,您需要确保此元素
不是最后一个在数组
中。
演示:
这是一个工作演示示例:
var arr = [
{ id: "Racer-101", rank: "1"},
{ id: "Racer-102", rank: "2"},
{ id: "Racer-103", rank: "3"},
{ id: "Racer-104", rank: "4"},
{ id: "Racer-105", rank: "5"},
{ id: "Racer-106", rank: "6"},
{ id: "Racer-107", rank: "7"},
{ id: "Racer-108", rank: "8"},
{ id: "Racer-109", rank: "9"}
];
function moveUp(id) {
let index = arr.findIndex(e => e.id == id);
if (index > 0) {
let el = arr[index];
arr[index] = arr[index - 1];
arr[index - 1] = el;
}
}
function moveDown(id) {
let index = arr.findIndex(e => e.id == id);
if (index !== -1 && index < arr.length - 1) {
let el = arr[index];
arr[index] = arr[index + 1];
arr[index + 1] = el;
}
}
moveDown("Racer-101");
moveUp("Racer-103");
console.log(arr);
关于javascript - 按索引上下移动数组对象/元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53533715/