jQuery数据()不能全局工作
问题描述:
我有两个函数添加到jQuery本机方法,并使用jquery data()方法来存储信息以检索后者。jQuery数据()不能全局工作
事情是我不想存储属性,如果它已被存储。
所以我必须:
$.fn.foo = function() {
if(!$.hasData(this)) {
$.data(this, 'width', this.css('width'));
$('#test').append('foo : Added to "data"<br>');
}
}
$.fn.bar = function() {
if(!$.hasData(this)) {
$.data(this, 'width', this.css('width'));
$('#test').append('bar : Added to "data"<br>');
}
}
$('element').foo();
$('element').bar();
但它输出 “添加到数据” 的两倍,而不是一次。看起来$ .data()根本不起作用。我应该如何调整代码以使数据在全球范围内运行?
这里的的jsfiddle:http://jsfiddle.net/e9e9vbnn/
答
$.data()需要dom元素引用作为第一个参数,而不是一个jQuery对象。插件方法this
内将引用被调用的jQuery包装器对象,而不是dom元素引用。
$.fn.foo = function() {
//also return this to maintain chanability
return this.each(function() {
if (!$.hasData(this)) {
$.data(this, 'width', $(this).css('width'));
$('#test').append('foo : Added to "data"<br>');
}
})
}
$.fn.bar = function() {
return this.each(function() {
if (!$.hasData(this)) {
$.data(this, 'width', $(this).css('width'));
$('#test').append('bar : Added to "data"<br>');
}
})
}
$('#element').foo();
$('#element').bar();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='test'></div>
<div id='element'></div>
我参访你以前那么繁琐answser与眼前这个[0],这是我现在使用的,它的工作好了!谢谢 !! – lapin 2014-09-30 08:12:13