[英]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. 我正在玩jQuery
$.data
函数,我遇到了麻烦。 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: 如果我使用
elem.data(key)
函数,它可以正常工作,如下所示:
(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 elem.data
is 10x slower than $.data(elem)
: http://paulirish.com/2009/perf/ 但我刚刚看到Paul Irish的幻灯片,声称
elem.data
比$.data(elem)
慢10倍: http : elem.data
(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/ 这是jsFiddle: http : //jsfiddle.net/TdJHq/
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. 每当你调用
$(selector)
,你都在创建一个新的 jQuery对象,它与你附加数据的对象不同。
Here is a simple example: 这是一个简单的例子:
$.data($('#test'),'test','hej');
alert($.data($('#test'),'test'));
It will give you undefined
. 它会给你
undefined
。
That is why $.data
expects a DOM element and not a jQuery object. 这就是
$.data
期望DOM元素而不是jQuery对象的原因。 No matter how you retrieve a certain DOM element, the reference is always the same. 无论您如何检索某个DOM元素,引用始终是相同的。
So either pass the DOM element ( $('#test')[0]
) or better , use $('#test').data()
. 因此,要么传递DOM元素(
$('#test')[0]
)或更好 ,请使用$('#test').data()
。
jQuery.data ( doc jQuery.data ) works on DOM elements, not on jQuery elements. jQuery.data( doc jQuery.data )适用于DOM元素,而不适用于jQuery元素。 So you must extract the real element under your jQuery selector.
所以你必须在jQuery选择器下提取真实元素。
obj.text($.data(obj[0],'test'));
This is what @alexl explained. 这是@alexl解释的内容。
But there is also a .data() method, that works on a jQuery selector, so you could use: 但是还有一个.data()方法,它适用于jQuery选择器,所以你可以使用:
// getter
obj.text($obj.data('test'));
// setter
obj.text($obj.data('test','toto'));
And you may have mixed both. 而且你可能两者兼而有之。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.