为jQuery的$ .data()存储多个值的最佳方式是什么? [英] What's the best way to store multiple values for jQuery's $.data()?

查看:157
本文介绍了为jQuery的$ .data()存储多个值的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在大量div上存储多个(10+)值,那么将它们全部存储在单个对象中还是作为单独的值更为最佳?



单一对象

  $(#div_id)。data(data,{ foo:1,bar:2}); 

分隔值


$ b $
.data(bar,2);
.data(foo,1)

每种方法的权衡是什么?这些属性中的一些将被频繁访问(例如在事件回调期间,例如拖动)。

解决方案

如果两种方法都很容易在你的代码中使用,去存储单个对象。它避免了每次需要一个值时调用 data()方法的额外开销。这样,您可以通过调用 data()来获取映射对象,然后根据需要从该对象中检索多次,而无需调用 data()再次。



data()方法使用对象将元素映射到引擎盖下的键/值,因此它不会自动对您的映射对象进行任何性能改进。


If storing multiple (10+) values on a large number of divs, is it more optimal to store them all in a single object, or as separate values?

Single Object:

$("#div_id").data("data", {foo:1, bar:2});

Separate Values:

$("#div_id")
  .data("foo", 1)
  .data("bar", 2);

What are the trade-offs of each method? Some of these attributes will be accessed frequently (during event callbacks like dragging, for instance).

解决方案

If both approaches are as easy to use in your code, go for storing a single object. It avoids the extra overhead of calling the data() method every time you need a value. This way, you can fetch the mapping object with one call to data(), and then retrieve values from this object as many times as you want without having to call data() again.

The data() method uses objects to map elements to keys/values under the hood, so it does not offer any performance improvements over managing a mapping object yourself.

这篇关于为jQuery的$ .data()存储多个值的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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