简体   繁体   中英

creating new elements with html5 data attributes defined in DOM

I want to create a new element with html5 data attributes defined, however they are not showing in the DOM (unlike when using say .addClass). is this intended behavior?

this creates an element without the data-foo attributs:

-> $("<div>foo</div>").data('foo', 'bar').addClass('class')
=> <div class="class">foo</div>

i had to declare it in the constructor

-> $("<div data-foo='bar'>foo</div>").addClass('class')
=> <div class="class" data-foo="bar">foo</div>

shouldn't the .data method work do the same?

From here:

4 . No jQuery data API ever changes HTML5 data-* attributes.

Most uses of .data() and .removeData() are still for the original purpose of associating data with DOM elements in memory. Updating DOM attributes each time data was changed would slow things down for no good reason. Also, it's not even possible to serialize all data types that might be attached to a DOM element, such as functions, references to other DOM elements, or custom JavaScript objects.

Rule: To update or remove HTML5 data-* attributes, use jQuery's .attr() or .removeAttr() methods.

So, use the usual attr ...

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