Can't call $.data on object inside function
I'm playing around with the jQuery $.data
function, and I'm running in to some trouble. If I do like this:
(function($){
$.fn.testData = function() {
var obj = $(this);
obj.text($.data(obj,'test'));
}
})(jQuery);
var element = $("#test");
$.data(element,'test','hej');
element.testData();
this comes out as undefined. Why?
EDIT:
It works just fine if I use the elem.data(key)
function, like this:
(function($){
$.fn.testData = function() {
var obj = $(this);
obj.text(obj.data('test'));
}
})(jQuery);
var element = $("#test");
element.data('test','hej');
element.testData();
but I just saw an slideshow by Paul Irish, which claims that 开发者_StackOverflow中文版elem.data
is 10x slower than $.data(elem)
:
http://paulirish.com/2009/perf/
(function($){
$.fn.testData = function() {
var obj = $(this);
obj.text($.data(obj[0],'test'));
}
var element = $("#test");
$.data(element[0],'test','hej');
element.testData();
})(jQuery);
Here is the jsFiddle: http://jsfiddle.net/TdJHq/
jQuery.data (doc jQuery.data) works on DOM elements, not on jQuery elements. So you must extract the real element under your jQuery selector.
obj.text($.data(obj[0],'test'));
This is what @alexl explained.
But there is also a .data() method, that works on a jQuery selector, so you could use:
// getter
obj.text($obj.data('test'));
// setter
obj.text($obj.data('test','toto'));
And you may have mixed both.
The problem is that you are creating different objects for attaching and retrieving the data. Whenever you call $(selector)
, you are creating a new jQuery object and this it will be different than the one you attached the data to.
Here is a simple example:
$.data($('#test'),'test','hej');
alert($.data($('#test'),'test'));
It will give you undefined
.
That is why $.data
expects a DOM element and not a jQuery object. No matter how you retrieve a certain DOM element, the reference is always the same.
So either pass the DOM element ($('#test')[0]
) or better, use $('#test').data()
.
精彩评论