JavaScript insertAt 位置

标签 javascript jquery indexing append

假设我有一个包含一堆有序元素的集合,那么在其抽象顺序位置处插入另一个新子元素的常用方法是什么?

使用 dom 库 $(new).eq($(new).data('orderPosition')); 不起作用,因为它不是有效的索引。

// Add this element to it's logic position in the collection:
<div data-order-position="10"></div>

// The collection
<div id="myCollection">
   <div data-order-position="4"></div>
   <div data-order-position="67"></div>
   <div data-order-position="81"></div>
   <div data-order-position="82"></div>
   <div data-order-position="761"></div>
</div>

我的真实收藏包含大约 400 个元素。

最佳答案

我认为使用整数数组可能是最有效的方法。您可以在数组中的某个位置维护已排序元素的常量列表(甚至可以根据需要继续排序):

//Array of positions
var positions = [];

//Initially set up the array in question
//divs are already sorted, as we know
$("#myCollection div").each(function () {
   positions.push(parseInt(this.dataset.orderPosition)); 
});

//Create the new node we want to insert (in your case it may already exist)
var $new = $("<div>").data('order-position', 10).text(10);

//Append the new node index (if node already exists, just use `.data` as above)
positions.push(10);

//Yes, for whatever reason JS sorts by string and not number by default.
//There may also be a more efficient way to add the integer in the correct spot
//without having to sort all over again, but this is fast enough
positions.sort(function (a, b) {
    return a - b;
});

//Insert the new node!
$("#myCollection div").eq(positions.indexOf(10) - 1).after($new);

http://jsfiddle.net/ExplosionPIlls/ULEFX/

关于JavaScript insertAt 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14762613/

相关文章:

javascript - 如何调用对象中的方法

javascript - express js 静态相对父目录

javascript - 加载脚本时显示 'Loading' 图标

javascript - jquery 检测显示或可见性的变化

mysql - 优化大表(75M+ 行)上的简单 mysql select

javascript - 基于 React JS 组件的样式

javascript - 在 Angular JS 应用程序中,如何处理服务器没有响应的情况?

javascript - Google Chrome 扩展示例

python - 使用 Keras ImageDataGenerator 预测进行索引会引发不可散列类型错误

database - 在 Access 2010 中创建具有引用完整性的关系时出现“索引过多”错误