简体   繁体   English

使用jQuery.data

[英]Use of jQuery.data

Well, I admit: I've extensively used jQuery.attr to store custom data in DOM elements in many, many scripts. 好吧,我承认:我已广泛使用jQuery.attr在多个很多脚本中的DOM元素中存储自定义数据。 I'm wondering if convert all my script to use jQuery.data instead of jQuery.attr. 我想知道是否将我的所有脚本转换为使用jQuery.data而不是jQuery.attr。 As far as I understand, the advantages of jQuery.data are: 据我所知,jQuery.data的优点是:

  • produce neat and valid HTML code 生成整洁有效的HTML代码
  • can store any type of data (objects, array,...) on elements 可以在元素上存储任何类型的数据(对象,数组,...)

The main advantage of custom attributes are: 自定义属性的主要优点是:

  • If WEB pages are not strict HTML, I can produce HTML code with custom attributes on the server 如果WEB页面不是严格的HTML,我可以在服务器上生成带有自定义属性的HTML代码
  • In firebug it's easy to inspect my HTML code in search of my custom attributes 在firebug中,很容易检查我的HTML代码以搜索我的自定义属性

Can someone tell me if I miss something or if exists issues that makes use of jQuery.data highly preferable? 有人能告诉我,如果我错过了某些内容,或者是否存在使用jQuery.data的问题?

You pretty much got it. 你差不多了。 But do you know every HTML attribute? 但是你知道每个 HTML属性吗? There are a lot of attributes that are used by screen-readers and other usability tools that are not standard (yet). 屏幕阅读器和其他非标准(可用)的可用性工具使用了很多属性。 What happens when you accidentally use the role attribute and a screen-reader picks that up? 当你不小心使用role属性并且屏幕阅读器选择了这个时会发生什么? Using $.data isn't only neater, it's safer for you and makes more sense. 使用$.data不仅更整洁,更安全,更有意义。

EDIT: I learned something last night that is pertinent to this question. 编辑:我昨晚学到的东西与这个问题有关。 In HTML5, you ca specify custom attributes for storing data. 在HTML5中,您可以指定用于存储数据的自定义属性。 These custom attributes must be specified using the prefix "data-". 必须使用前缀“data-”指定这些自定义属性。 See the spec for more detailed information. 有关更多详细信息,请参阅规范

What this means, is that you do not have to go back and change all of your old code, because you will never have to worry about overlapping with other attributes if you prefix with "data-". 这意味着,您不必返回并更改所有旧代码,因为如果您使用“data-”作为前缀,则永远不必担心与其他属性重叠。 However, if you need to store more complicated data types than strings, use $.data . 但是,如果您需要存储比字符串更复杂的数据类型,请使用$.data

我认为你不会错过任何东西,但在dom元素属性上存储数据总是一个不好的做法,所以我认为你应该使用$ .data函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM