如何在拼接/排序数组时保持jQuery DOM元素引用?

How can I keep a jQuery DOM element reference when splicing/sorting an array?

本文关键字:jQuery DOM 元素 引用 拼接 数组 排序      更新时间:2023-09-26

我有一个对象数组。这些对象的属性之一是对DOM元素的jQuery引用,该元素在任何给定时间可能会或可能不会实际附加到DOM;

例如:

Array = [{
      name : 'whatever 1',
      element : $('<div id="item_1" class="item"><img src="" /></div>')
},
{
     name : 'whatever 2',
     element : $('<div id="item_2" class="item"><img src="" /></div>')
}];

当这个数组未被触及时,我可以毫不费力地将这些元素分离并附加到DOM中,也可以在元素上使用标准的jQuery方法。

例如:

Array[0].element.find('img');

…会很好。

但是,如果我对这个数组进行排序或拼接,就会丢失引用。

我理解这种情况发生的原因,但我想知道的是,如果周围有这样的方式,这个元素可以不断地改变,附加,分离,修改,而排序或拼接整体数组本身?

提前感谢。

编辑:

下面是我的rearrange函数的代码示例:

    rearrangeItems : function(){
                        var self = this;
                        var offset = 0;

                        // get number of items that are less than insertindex
                        for(var i = 0; i < self.cache.selecteditems.length; i++) {
                                  if(self.cache.selecteditems[i] < self.cache.rearrangepos){
                                      offset++;
                                  }
                        }
//subtract the offset from the intended insertion index
            var rearrangeindex = self.cache.rearrangepos - offset;
            var removedItems = [];
//sort the selected element indexes into ascending order
            self.cache.selecteditems.sort(function (a, b) {
                if (a < b) return -1;
                else if (b < a) return 1;
                return 0;
            });

//remove the selected array elemens from the overall array and push them into the temporary array    
            for(var i = 0; i < self.cache.selecteditems.length; i++) {
                var index = self.cache.selecteditems[i];
                removedItems.push(self.cache.items.splice(index - removedItems.length, 1)[0]);
            }
//Add the selected array elements back into the main array at the correct insertion point
            self.cache.items.splice.apply(self.cache.items, [rearrangeindex, 0].concat(removedItems));
    }

当调用该函数时,所有数组元素将完全按预期顺序重新排序。

在重新排序之前,我可以做以下操作:

self.cache.items[index].html.find('img'); 
然后,它将导致一个空对象(html属性相当于我上面例子中的元素属性)。

我会使用ID,因为你有一个。我不知道这是否是最干净的解决方案,但它会起作用。

像这样调用你的例子:

$('#' + Array[0].element.attr('id')).find('img');

遗憾的是,这是我自己的愚蠢。在我的代码中,我错误地引用了元素。

我实际上是这样做的:

self.cache.items[index].html.find('#image_' + index); 

在元素重新排序之后,我故意在之后重置索引,因此在排序/重新排序之后调用此函数时,元素是不正确的。

通过切换到类选择器,一切都固定了。

self.cache.items[index].html.find('.image_item'); 

多尴尬啊!我向大家道歉。