在 jQuery 中使用 'data-attribute' 而不是 $.data 的优势是什么? [英] What is the advantage of using 'data-attribute' over $.data in jQuery?

查看:23
本文介绍了在 jQuery 中使用 'data-attribute' 而不是 $.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 中添加 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-attribute' 而不是 $.data 的优势是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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