JQuery .data() how to work question

后端 未结 2 341
粉色の甜心
粉色の甜心 2021-01-24 17:26

I have a question about .data(). In a stackoverflow answer, jquery saves data in cache object where cache index is suffixed with a hash of the dom element. For example, consider

2条回答
  •  天涯浪人
    2021-01-24 17:58

    The way in which jQuery data works is by storing all the data internal in a variable called cache. Each jQuery session creates a "expando" which is basically a random string like jquery161362319162 specific to that session. This is placed on each object in the DOM such as element.jquery161362319162 with a value of the index in cache.

    Here is a very basic example of roughly how it works. This will need a bit more work to add support for multiple data on an element, but you'll get the idea of how it works internally.

    var cache = []; // Stores all the data for each element
    var uid = 'jquery89437507043'; // random generated id,
                                   // jQuery uses a function to automatically
                                   // generate such a value
    
    function data(element, key, data)
    {
        if (data !== undefined) // We are setting data
        {
            var thisCache[key] = data;
            cache.push(thisCache)
            element[uid] = cache.length; // Place the index cache
                                            // for this data set on the element
        }
        else
        {
            return cache[element[uid]][key];
        }
    }
    

    Usage

    var div = $('div').get(0);
    data(div, 'test', { 'apple': 'juice' });
    
    alert(data(div, 'test').apple); // Will alert 'juice'
    

提交回复
热议问题