我使用jQuery存储数据的方式有优势吗? [英] Is there an advantage in how I store my data using jQuery?

查看:87
本文介绍了我使用jQuery存储数据的方式有优势吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道更多关于jQuery如何存储数据的信息。

I know understand more about how jQuery stores data.

做其中一项或另一项是否有任何好处:

Is there any advantage to doing one or the other of these:

$('#editCity').data('href', "xx");
var a = $('#editCity').data('href');

$('#editCity').attr('data-href', "xx");
var a = $('#editCity').attr('data-href');

另一个相关问题。

如果我有这个:

var modal = { x: 'xx', y: 'yy' };

我可以使用.data(..)存储吗?

Can I also store this using .data( .. ) ?

推荐答案

直接在DOM元素上存储属性值是有风险的,因为可能存在内存泄漏。无论如何,如果你正在使用jQuery,那么 .data()机制是跟踪每个元素信息的一种美妙而安全的方法。它也允许存储任意JavaScript数据结构,而不仅仅是字符串。

Storing property values directly on DOM elements is risky because of possible memory leaks. If you're using jQuery anyway, the .data() mechanism is a wonderful and safe way to keep track of per-element information. It allows for storage of arbitrary JavaScript data structures too, not just strings.

edit —当您的HTML标记包含 data-foo 属性时,在访问密钥时会隐式读取这些属性。也就是说,如果你的HTML看起来像这样:

edit — when your HTML markup contains data-foo attributes, those are implicitly read when the keys are accessed. That is, if your HTML looks like this:

<div id="div1" data-purpose="container">

然后在jQuery中:

Then in jQuery:

alert( $('#div1').data('purpose') ); // alerts "container"

此外,jQuery还会对属性值进行一些智能分析。如果值看起来像一个数字,jQuery将返回一个数字,而不是一个字符串。如果它看起来像JSON,它会为您反序列化JSON。

Furthermore, jQuery will also do some "smart" analysis of the attribute values. If a value looks like a number, jQuery will return a number, not a string. If it looks like JSON, it de-serializes the JSON for you.

编辑—这是一个很好的技巧:在Chrome开发人员控制台(控制台视图)中,您可以键入JavaScript表达式并对其进行评估。评估始终在您正在处理的页面的上下文中完成。如果从元素视图中选择一个元素,则在控制台中,JavaScript符号 $ 0 将引用所选的DOM元素。因此,您始终可以通过转到控制台并键入以下内容来检查元素的数据映射:

edit — here's a good trick: in the Chrome developer console (the "Console" view), you can type JavaScript expressions and have them evaluated. The evaluation is always done in the context of the page you're working on. If you select an element from the "Elements" view, then in the console the JavaScript symbol $0 will refer to that selected DOM element. Thus you can always inspect the "data" map for an element by going to the console and typing something like:

$($0).data("something");

.data()函数,如果没有参数调用,返回所有键/值对:

The .data() function, if called with no parameters, returns all the key/value pairs:

$($0).data();

这篇关于我使用jQuery存储数据的方式有优势吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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