在jQuery中,相对于$ .data使用“数据属性"有什么优势? [英] What is the advantage of using 'data-attribute' over $.data in jQuery?

查看:109
本文介绍了在jQuery中,相对于$ .data使用“数据属性"有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道将数据分配给DOM而不是不分配给DOM的好处是什么

I was wondering what the advantage is of using data assignment to the DOM vs. NOT to the DOM

即假设我们说过HTML

i.e. Assume we have said HTML

<a id="foo" href="#">foo!</a>

//Set attr data-me so it's <a id="foo" data-me="yay" href="#">foo!</a>
$('#foo').attr('data-me', 'yay');

//Retrieve the data 'yay'
$('#foo').data('data-me');

直接分配外:

var myInput = $('#foo');    

//Add some data
$.data(myInput, 'data-me', 'yay');

//Retrieve the data 'yay'
$.data(myInput, 'data-me');

我的理解是,后面的MUCH更快,因此,当不需要DOM时,我看不出在整个DOM中添加data-someAttr的意义吗?

My understanding is that the later is MUCH faster and therefore I can't see the sense in adding data-someAttr all over the DOM when it's not required ?

推荐答案

它们具有不同的用途.是的,似乎可以将它们用于实现相同的目的,但是在本质上却存在差异.

They serve different purposes. Yes, it seems like they can be used to achieve the same thing, but under the hood there are differences.

  1. 虽然您可以保存简单值在属性中,您将无法保存DOM节点,因为您将创建

  1. While you can save simple values in attributes, you can not save DOM nodes, because you will create memory leaks. Neither can you save objects, arrays, functions, etc...

$.attr()可能比$('selector').data()快,但并不比低级方法jQuery.data()快.第一种数据方法比第二种方法具有更多的开销,但是第二种方法并没有承载第一种方法的所有功能.例如,它不会从data-属性中获取数据.

$.attr() might be faster than $('selector').data(), but it is not faster than the low-level method jQuery.data(). The first data method has much more overhead than the second, however the second one does not carry all the functionality of the first one. For example, it does not get the data out of the data- attributes.

因此,我认为最好在加载时使用data-属性,因此您可以使用$('selector').attr()提取数据,并使用$.data()处理应用程序状态.

Thus, I think it's best to use data- attributes at load time, so you can extract the data with $('selector').attr(), and handle the application state with $.data().

这篇关于在jQuery中,相对于$ .data使用“数据属性"有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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