本文介绍了jQuery从对象集合中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例代码,用于创建对象集合.

I have the following example code, creating a object collection.

如何移除其中一个对象?(例如, $TestList 看起来好像删除我"项从未存在过.我试过 .remove、.splice、.delete 等,但我被告知这不是一个函数.

How can I remove one of the objects? (e.g. $TestList would look as though the "delete me" item was never there.I've tried .remove, .splice, .delete etc but I'm told it's not a function.

执行 typeof($TestList) 会带回对象,而 typeof($TestList[0]) 似乎也有效.

Doing typeof($TestList) brings back object, and typeof($TestList[0]) also seems valid.

当然我不必在没有一件物品的情况下重新创建集合吗?

Surely I don't have to recreate the collection without one item?

(function($) { 

jQuery.QuickTest = {
    $TestList: {},
    build: function()
    {
        $TestList={};
        $TestList[0] = 
        {
            title: "part 1"
        };

        $TestList[1] = 
        {
            title: "delete me please"
        };

        $TestList[2] = 
        {
            title: "part 2"
        };

    }
}

jQuery.fn.QuickTest = jQuery.QuickTest.build;   

})(jQuery);

$(document).ready(function() {

$().QuickTest(
{
})
});

我们使用的是 jQuery 1.3.

We're using jQuery 1.3.

谢谢!

推荐答案

回顾

首先,您的代码应该做什么非常不明显,但这里有一些问题:

First of all, it's very non-obvious what your code is supposed to do, but here are some issues:

jQuery.QuickTest = {
    $TestList: {},
    build: function()
    {
        $TestList={};

你定义了 jQuery.QuickTest.$TestList,但是在 build() 里面你声明了一个 global 对象 $TestList.

You define jQuery.QuickTest.$TestList, but inside build() you declare a global object $TestList.

jQuery.fn 下声明的函数应该作用于一组匹配的元素(由 this 引用)并返回它;你的函数两者都没有.

Functions declared under jQuery.fn are supposed to act on a matched set of elements (referenced by this) and return it as well; your function does neither.

答案

回答您的一些问题:

  1. .remove() 是一个 jQuery 函数,用于从 DOM 中删除节点,需要在 jQuery 对象上调用.

  1. .remove() is a jQuery function that removes nodes from the DOM and needs to be called on a jQuery object.

.splice() 仅适用于 Array 并且即使您像访问 $TestList 一样访问它,它仍然只是一个 Object.

.splice() only applies to Array and even though you're accessing $TestList as if it were one, it's still just an Object.

.delete() 不是我知道的任何函数;-)

.delete() is not any function I know ;-)

可能的解决方案

要从 $TestList 中删除条目,您可以以这种方式使用 delete:

To delete an entry from $TestList you could use the delete in this fashion:

delete $TestList[1];

这篇关于jQuery从对象集合中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 03:48