为什么不更改jQuery $ .fn.data()更新相应的html 5 data- *属性? [英] Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?

查看:126
本文介绍了为什么不更改jQuery $ .fn.data()更新相应的html 5 data- *属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的例子来说明这种行为:

Here's a simple example to illustrate the behavior:

给定这个html标记:

Given this html markup:

<div data-company="Microsoft"></div>

和这个jQuery代码(使用jQuery 1.5.1):

and this jQuery code (using jQuery 1.5.1):

// read the data
alert($("div").data("company"));
// returns Microsoft <<< OK!

// set the data
$("div").data("company","Apple");
alert($("div").data("company"));
// returns Apple <<< OK!

// attribute selector
alert($("div[data-company='Apple']").length);
// returns 0  <<< WHY???

// attribute selector again
alert($("div[data-company='Microsoft']").length);
// returns 1  <<< WHY???

// set the attribute directly
$("div").attr("data-company","Apple");
alert($("div[data-company='Apple']").length);
// now returns 1 <<< OK!

由于jQuery自动将HTML5 data- *导入到jQuery的数据对象中,所以不应更新属性以及数据改变的时候?

Since jQuery automatically imports the HTML5 data-* into jQuery's data object, shouldn't the attributes be updated as well when the data changes?

推荐答案

通常,不需要往返 .data()如果您在使用.data()访问/设置/修改DOM元素上的数据方面一致。因此,为每个 .data()设置/修改操作( .data())避免访问DOM的性能开销是有意义的。 在内部将它的值存储在 jQuery.cache 中)。

Normally, there's not a need for roundtripping .data()'s if you're consistent in using .data() to access/set/modify data on DOM elements. For that reason, it makes sense to avoid the performance overhead of accessing the DOM for every .data() set/modify operation (.data() stores its values in jQuery.cache internally).

如果你想强制您可以订阅setData或changeData事件,然后将这些事件中的 .data()更新推送到相应的DOM元素 .attr()

If you want to force the roundtrip behavior yourself, you could subscribe to the "setData" or "changeData" events and then push the .data() update in those events through to the corresponding DOM element via .attr().

这篇关于为什么不更改jQuery $ .fn.data()更新相应的html 5 data- *属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆