Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .data() method

When I store an object like {a: 1, b: 2 } in jQuery's data, does it copy the object or save a reference to it?

I have a huge object and I want different elements to store different references from different points to the same object, and I don't want it to get copied.

Like

var obj = { 
    a: {
        one: 1, two: 2
    },
    b: {
        apple: 'yummy', banana: 'ehh'
    }
    c: {
        d: {
            'jQuery': jQuery
        }
        e: ['You get the point']
    }
};

$('div').data('info', obj.b);
$('#JQ').data('jq_reference', obj.c.d.jQuery);
like image 996
qwertymk Avatar asked Apr 17 '11 16:04

qwertymk


People also ask

What is a data method in Javascript?

The data() method attaches data to, or gets data from, selected elements. Tip: To remove data, use the removeData() method.

How read data attribute in jQuery?

Alternatively, you can also use the jQuery data() method (jQuery version >= 1.4. 3), to get the data-attribute of an element using the syntax like $(element). data(key) . That means in the above example to get the data-id using data() method you can use the statement like $(this).

How add data attribute in jQuery?

$('div'). attr('data-info', 1); $('div')[0]. setAttribute('data-info',1); In order to access an element with the attribute set, you can simply select based on that attribute as you note in your post ( $('div[data-info="1"]') ), but when you use .

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


1 Answers

According to my jsfiddle test, it stores a reference.

If I do this:

$('div').data('info', obj.b);
obj.b.apple = 'bleuch';
alert($('div').data('info').apple);

It alerts "bleuch", showing that a reference to the original object is being stored.

like image 84
Alnitak Avatar answered Sep 19 '22 13:09

Alnitak