Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

javascript - dataset vs .data - Difference?

I am reading some values in data attribute fields. I have seen two easy ways to read the data as shown below:

var webappData = document.getElementById('web-app-data'),
    rating = webappData.dataset.rating;

OR

var effectData = $('.effects-list li'),
    creative = effectData.filter('[data-creative]').data("creative");

My question is which of these has better performance or do they really differ?

I have a page with many data attributes that I am accessing and I would like to use the method that has the best performance.

Any guidance on understanding the difference between the two would be appreciated. While I am looking at performance specifically if there are other reasons to use one over the other I would like to know this as well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

dataset is a native property of an element that contains the data attributes, it's a new(ish) addition and as such is only supported in IE11+, Chrome 8+, FF 6+ etc.

A more cross browser solution would be to get the attribute directly

webappData.getAttribute('data-rating');

data() is a jQuery method, and other than using the HTML5 data attribute to set the inital value if none exists internally, it has nothing in common with dataset.

data() stores whatever data you pass it in an internal object created by jQuery, so this for instance would fail

$(element).data('key', 'value');

element.dataset.key // undefined

as the data is not stored in the attributes at all, but internally by jQuery.
The jQuery equivalent of getting and setting the data attribute would be attr()

$(element).attr('data-key', 'value');

The native methods are probably faster, but as they are not really comparable to jQuery's data() it doesn't really matter, but for getting the data attribute I would think the fastest method with the best browser support would be

var rating = webappData.getAttribute('data-rating');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...