如何将对象添加到指定索引处的 jQuery 集合?

How do you add an object to a jQuery collection at a specified index?

我正在创建一个代表数据绑定 table 的 JavaScript class,使用 jQuery 来处理 DOM 操作。 class 有一个 $table.$body.$rows 属性,我在其中保存 table 的 jQuery 换行的集合,以避免执行 $table.$body.children('tr')每当添加或删除一行时调用。当一行进入或离开编辑模式时,我需要能够从 $table.$body.$rows 属性 添加和删除对象,我用 jQuery 的 .add().not() 方法。

但是,当正在编辑的行不在 table 的末尾时,这些方法是不够的,因为 .add() 方法将新项目添加到内部集合的末尾在 jQuery 实例中维护。为了确保 $table.$body.$rows 集合的顺序正确,我需要能够 插入 新项目到 jQuery 集合中的指定索引处。这样的方法是否已经存在,还是我必须自己编写?

我可以让 HTMLTableSectionElement.rows 属性 为我跟踪行,并在必要时简单地将特定行包装在 jQuery 对象中,但这似乎效率低下。这就提出了一个次要问题:无论如何,像 .children('tr') 这样的调用有多昂贵,每次添加或删除一行时,我最好重新分配 $table.$body.$rows 吗?

您可以在原生数组对象上使用 splice 函数。

arr.splice(index, 0, item); 将在指定的 index.

处将 item 插入 arr
  1. 技术上,jQuery do add splice() to jQuery.fn, but it isn't documented. They almost removed it 最近从 public 界面,但决定不这样做;

    We want to avoid the appearance that using these methods [jQuery.fn.{push,sort,splice}] is encouraged, but we don't want to remove them either.

    ...随心所欲。

  2. 可以使用Array.prototype.splice.call,例如:

    Array.prototype.splice.call($table.$body.$rows, 3, 0, newItem);
    

    ...我看不出那有什么错。

  3. 尽管老实说,我认为您正在尝试解决一个不存在的问题。

    I could just let the HTMLTableSectionElement.rows property keep track of the rows for me and simply wrap a particular row in an jQuery object when necessary

    ...我会这样做。在修改行时调用 .children('tr') 并更新 $table.$body.$rows 不会终止您的应用程序。