在DOM中存储数据 - 自定义属性或.data()[复制]

时间:2021-06-15 16:57:20

Possible Duplicate:
jQuery Data vs Attr?

可能重复:jQuery Data vs Attr?

I'm working on a project where I plan on storing small amounts of data in the DOM. I'm specifically using it to attach a numerical value to a DOM element to be easily accessed elsewhere.

我正在开发一个项目,我计划在DOM中存储少量数据。我特意使用它将数值附加到DOM元素,以便在其他地方轻松访问。

Is it better to insert a custom attribute like so:

插入自定义属性是否更好:

 $('#storeThingsHere').attr('data-count', superArray.length);

Or to utilize jquery's .data() function?

或者使用jquery的.data()函数?

 $('#storeThingsHere').data("count", superArray.length);

I know both can be used, but I want to utilize best practices while also choosing the most efficient method possible. Is there a particular benefit to one over the other, or possibly another better option to store this small amount of data in the DOM?

我知道两者都可以使用,但我想利用最佳实践,同时选择最有效的方法。是否有一个特别的好处,或者可能是另一个更好的选择,在DOM中存储这么少的数据?

1 个解决方案

#1


4  

Use data. Any type can be stored using data as jQuery uses an internal object to store them, whereas only strings can be stored using attr.

使用数据。任何类型都可以使用数据存储,因为jQuery使用内部对象来存储它们,而只有字符串可以使用attr存储。

Also, data() will most likely be faster due to it not having to reference the DOM for setting/getting, although I've not tested this.

此外,data()很可能会更快,因为它不必引用DOM进行设置/获取,尽管我没有对此进行测试。

#1


4  

Use data. Any type can be stored using data as jQuery uses an internal object to store them, whereas only strings can be stored using attr.

使用数据。任何类型都可以使用数据存储,因为jQuery使用内部对象来存储它们,而只有字符串可以使用attr存储。

Also, data() will most likely be faster due to it not having to reference the DOM for setting/getting, although I've not tested this.

此外,data()很可能会更快,因为它不必引用DOM进行设置/获取,尽管我没有对此进行测试。