问题
I was wondering what the advantage is of using data assignment to the DOM vs. NOT to the DOM
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');
Over and above direct assignment:
var myInput = $('#foo');
//Add some data
$.data(myInput, 'data-me', 'yay');
//Retrieve the data 'yay'
$.data(myInput, 'data-me');
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 ?
回答1:
They serve different purposes. Yes, it seems like they can be used to achieve the same thing, but under the hood there are differences.
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()
might be faster than$('selector').data()
, but it is not faster than the low-level methodjQuery.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.
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()
.
回答2:
I'm not a guru, that' s for sure... but it appears to me that two obvious differences are the time/environment when the 'data' is set, and the structure(type) of data that will be stored/accessed.
Concider this scenario:
<a id="foo" data-me="some string data" href="#">foo!</a
This pice of html was maybe generated on the server side. If so,only the server side needs to know about the 'data-me' value origin. One limitation is that the attribute must be a string , or a string representation of an object (JSON)
var customData =
{
date:new Date(),
otherProp:'some value',
someFunc: function(a,b)
{
// function dody
}
};
$('#foo').attr('data-me', customData)
From the javascript(medium), at a certain moment, triggered by a certain event(time), you can use jQuery to bind a dom element to a given object (not necessarily a string)
So the latter way ($('#foo').attr('data-me', customData)), removes the 'only string' limitation and allows you to bind to a dom element any kind of js object , even functions.
来源:https://stackoverflow.com/questions/7266663/what-is-the-advantage-of-using-data-attribute-over-data-in-jquery