jQuery remove object from object collection

有些话、适合烂在心里 提交于 2021-01-27 05:15:08

问题


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

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.

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(
{
})
});

We're using jQuery 1.3.

Thanks!


回答1:


Review

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={};

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

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.

Answers

An answer to some of your questions:

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

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

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

Possible solution

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

delete $TestList[1];



回答2:


use delete myObject, not myObject.delete



来源:https://stackoverflow.com/questions/16586852/jquery-remove-object-from-object-collection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!