insertBefore函数用于数组和/或HTMLCollections?

问题描述 投票:0回答:3

[van JavaScriptjQuery中是否存在一个与Node.insertBefore()类似的功能,但对于数组和/或HTMLCollections?

示例可能类似于:

var list = document.getElementsByClassName("stuff");
var nodeToMove = list[0];
var otherNode = list[4];
list.insertBefore(nodeToMove, otherNode);

基本上,我试图在不操纵实际DOM的情况下执行insertBefore(),因为我希望更改仅在特定条件下才适用于DOM。如果满足这些条件,那么我将在实际节点上执行insertBefore()

为澄清起见,我正在寻找一个函数,该函数可以在数组的给定索引中插入元素before目标元素,而不一定是给定索引at。我使用splice()看到的示例通常在给定索引处插入元素,这有时会将元素放在目标元素之前,有时放在目标之后,具体取决于最初要移动的元素在数组中的位置。我正在寻找可以可靠地将元素移动到[[before目标元素。

的东西。
javascript jquery html dom
3个回答
0
投票
HTMLCollection没有insertBefore方法。 jQuery可以将任何jQuery方法都应用于单个元素以及多个元素。

https://api.jquery.com/insertBefore/

0
投票
没有一个单一的方法可以一步完成,但是没有必要。如果将集合转换为数组,则可以调用Array.prototype.splice()方法以实现相同的结果。

这里是一个例子:

Array.prototype.splice()
而且,有了这些知识,您就可以创建自己的更容易调用的函数:

let ary = [1,2,3,4,5]; // Swap 2 and 3 // Start at the 3rd item and remove one item (3). // Store the removed item let removed = ary.splice(2,1); // Start at the second item, don't remove anything, insert the removed // item at that position ary.splice(1,null,removed[0]); // Log the result console.log(ary);

0
投票
您需要获取所需的索引,然后使用Array.splice。

我自己,我会做这样的事情:

let ary = [1,2,3,4,5]; function insertBefore(ary, newItem, target){ ary.splice(target,null,newItem); } // Insert 999 before the 3rd array item insertBefore(ary,999,2) console.log(ary);

请随时在浏览器的控制台中进行尝试。请注意,我在数组中使用了const,因为它将变量的类型固定为数组,但允许我对其进行操作。

const myArr = ['Aurore', 'Dimitri', 'Alban', 'Frédéric']; const insertBeforeThis = 'Alban'; const eltToInsert = 'Laura'; const index = myArr.findIndex(name => name === insertBeforeThis); myArr.splice(index, 0, eltToInsert);

MDN: Array.prototype.findIndex()

祝您编码愉快!

© www.soinside.com 2019 - 2024. All rights reserved.