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

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

转载自IT宝库 https://www.itbaoku.cn/post/1009432.html

问题描述

在查看源代码时,我注意到 ‘toggle’ 应该使用 jQuery._data 来存储元素的状态.我检查了 chrome 中的 jQuery.cache 对象,发现该元素的数据对象下还有另一个对象,前面有一个单词 jQuery,我猜它是唯一标识它的数字.但是,我没有看到有关元素状态的数据.只需{olddisplay: ‘block’}.关于 jQuery._data 的目的及其本身如何工作的任何线索?

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

推荐答案

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 );
},

它只是调用 jQuery.data 并强制第四个参数(即隐私)为真.检索数据时,如果设置了 pvt 标志,则检索方式略有不同…data() 的公共接口不公开 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 ];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值