在浏览源代码时,我注意到“toggle”据说使用 jQuery._data
来存储元素的状态。我检查了 chrome 中的 jQuery.cache 对象,发现该元素的数据对象下面还有另一个对象,前面带有单词 jQuery 和一个我猜测唯一标识它的数字。但是,我没有看到有关元素状态的数据。只需{olddisplay: 'block'}
。关于 jQuery._data 的目的及其本身如何工作的任何线索?
我一整天都在盯着源代码......请不要告诉我查看源代码。我的眼睛和大脑会感谢你。
最佳答案
jQuery 使用 _data 来为其存储在对象上的数据设置“pvt”标志。使用 pvt
以便当您从对象请求公共(public)数据时,不会返回 pvt 数据。这是为了防止 jQuery 对 .data()
机制的内部使用(就像切换一样)影响 .data()
的公共(public)使用。
您可以在 jQuery 源代码中看到此声明:
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
这只是调用 jQuery.data
并强制第四个参数(即隐私)为 true。检索数据时,如果设置了 pvt
标志,则检索方式略有不同。 .data()
的公共(public)接口(interface)不会公开 pvt
标志。
您可以在 jQuery.data()
的这一部分中看到 pvt
处理的示例:
// 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);
}
}
然后在同一个函数中,此评论非常具有描述性:
// 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 ];
}
关于javascript - jQuery.data 和 jQuery._data (下划线数据)有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7788353/