dataset vs .data - 差异? [英] dataset vs .data - Difference?

查看:116
本文介绍了dataset vs .data - 差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取数据属性字段中的一些值。我已经看到了两种简单的方法来读取数据,如下所示:

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.

推荐答案

dataset 是包含数据属性的元素的本机属性,它是一个新的(ish)添加,因此仅支持IE11 +,Chrome 8 +,FF 6+等。

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() 是一个jQuery方法,除了使用HTML5数据属性设置初始值(如果不存在)在内部,它与数据集没有任何共同之处。


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()将您传递给它的任何数据存储在jQuery创建的内部对象中,所以这就是失败

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

因为数据不是存储在属性中,但内部由jQuery存储。

获取和设置数据属性的jQuery相当于 attr()

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');






原生方法可能更快,但是因为它们它与jQuery的 data()无法真正相提并论它并不重要,但是为了获得数据属性,我认为最好的浏览器支持方法是


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');

这篇关于dataset vs .data - 差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆