jQuery.data和jQuery._data(下划线数据)有什么区别?

THE*_*had 25 javascript jquery

在浏览源代码时,我注意到'toggle'应该jQuery._data用来存储元素的状态.我检查的jQuery.cache对象中铬,发现元素的数据对象有另一个目标下它由字的jQuery前面添加一个数字,我猜唯一标识.但是,我没有看到关于元素状态的数据.简单{olddisplay: 'block'}.关于jQuery._data的目的以及它本身如何工作的任何线索?

我一整天都在盯着源头......请不要告诉我查看来源.我的眼睛和大脑会感谢你.

jfr*_*d00 47

jQuery使用_data为它存储在对象上的数据设置'pvt'标志.使用它pvt是为了在从对象请求公共数据时,不返回pvt数据.这是为了保持jQuery对.data()机制的内部使用(如切换所做的那样)来影响公众的使用.data().

你可以在jQuery源代码中看到这个声明:

// For internal use only.
_data: function( elem, name, data ) {
    return jQuery.data( elem, name, data, true );
},
Run Code Online (Sandbox Code Playgroud)

其中只调用jQuery.data并强制第四个参数(即隐私)为真.检索数据时,如果pvt设置了标志,则以稍微不同的方式检索它.公共接口.data()不公开pvt标志.

您可以pvt在以下部分中看到处理示例jQuery.data():

// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
    if ( pvt ) {
        cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
    } else {
        cache[ id ] = jQuery.extend(cache[ id ], name);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在同一个函数中,这个评论非常具有描述性:

// Internal jQuery data is stored in a separate object inside the object's data
// cache in order to avoid key collisions between internal data and user-defined
// data
if ( pvt ) {
    if ( !thisCache[ internalKey ] ) {
        thisCache[ internalKey ] = {};
    }
    thisCache = thisCache[ internalKey ];
}
Run Code Online (Sandbox Code Playgroud)