简体   繁体   中英

Best practices for data association with HTMLElement objects?

I came across 3 ways to store any data with HTMLElement object.

Can someone please suggest the best practice to associate any data with element object?

I prefer number 3 because it doesn't set any HTML attribute as in the case of 1 and 2. It's just like setting and getting any property on the object.

  1. Use setAttribute('nonStandardDataProperty')
  2. Use dataset property of HTMLElement object for example dataset.x for data-xattribute
  3. HTMLElement is object, so define any property and it will serve as data storage for that element

Option #2 seems to me to be the most "standards-compliant", if that's what you're looking for; plus, it allows you to set those attributes from within the HTML while still maintaining valid markup. It's generally my preference, but it's really whatever works best for you in your situation: if it works, go with it.

I would use option #1 because it's the most portable.

However I would use HTML5's data- prefix for those custom attributes for compatibility with jQuery's .data() method.

第三种选择是将数据存储在DOM中,如果数据不是很大,这可能不是一个坏主意。如果是,那么存储和检索数据可能会影响应用程序的性能。

I guess the best way is using HTML5 data-* Attributes and jQuery's .data() function. It will probably have the best way to store data in HTML elements built-in and update to latest technologies in the future, so you can lean back and just be productive

<div id="myDiv" data-my-var="my-var-value"></div>

can be used in JavaScript like this: (jQuery required)

console.log( $( '#myDiv' ).data( 'my-var' ) )

Edit: and set like this

$( '#myDiv' ).data( 'my-var', 'my-new-var-value' );

which will also update the data-* attribute in this case

Option 4: store an identifier on the DOMNode which you can use to look things up in a detached map (yes, this is how jQuery does it - on top of importing all data-* attributes during init, of course).

Going with #3 is fine if you mind your property names. #2 should only allow Integer and String values, #1 might have the same issue.

I'd go with #4, simply because I don't like the odds of a new spec popping up and claiming a property name I used for my own data…

Twitter Bootstrap uses option one.

Take a look at Twitter Bootstrap document, you will see plenty uses of storing data in the none-standard property html elements.

example

<ul class="dropdown-menu pull-right" role="menu" aria-labelledby="dLabel">
  ...
</ul>


<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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