[英]Saving a local data in a JQuery function
我想创建两个JQuery函数。 其中一个将使用在另一个函数中创建的数据。 说:
jQuery.fn.myScroller = function (child) {
var $moveable = this.children(child);
var $children = this.children(child).children();
posl = posl.replace('px', '');
post = post.replace('px', '');
var varList = [];
$children.each(function () {
var currVar = {};
currVar.w = $(this).width();
varList.push(currVar);
});
// I want to save varList variable somehow.
this.varList = varList; // (1)
};
jQuery.fn.scrollUnitLeft = function () {
// Now I need to use this varList if this function called
// But the following returns undefined.
// However, I've saved it inside this at (1)
console.log(this.varList)
// More code...
}
$('#main_div').myScroller("#dummydiv");
$('#main_div').scrollUnitLeft();
正如我在代码注释中所解释的那样,这是行不通的。
我怎样才能做到这一点?
按照建议创建名称空间或全局变量对我来说并不干净。 您已经在扩展jQuery,因此使其成为jQuery变量:
jQuery.fn.varList = varList;
编辑:我真的不知道jQuery内部。 如果fn
仅用于函数,则将其放入jQuery
本身或编写一个getter
jQuery.fn.getVarList = function () {
return varList;
}
您可以在全局范围内创建名称空间:
window.yourNamespace = {};
然后将您的varList
变量放在该命名空间中:
yourNamespace.varList = []; //Whatever you want here
这样,变量将可用于您的两个函数(或与此相关的任何函数)。
您this
理解对我来说似乎有点不足(对不起,您可能比我更有经验)! this
是指函数的调用者。 两次都是div main_div
。 尝试使用在两个函数外部都声明的全局变量,或者在第一个函数中使用div上的data
属性,然后在第二个函数中访问该值。
当您运行jQuery函数时, this
是指在每种情况下使用的jQuery对象实例。
在您的代码中,创建两个jQuery对象实例(每个$(...)
调用一个),因此数据在第一个实例中设置,因此第二个实例不可用。
如果要在同一个jQuery对象实例上运行两个方法,则它们将按预期工作。
jQuery.fn.mySet = function(){
this.myVar = this.attr('id');
};
jQuery.fn.myGet = function(){
console.log(this.myVar);
}
$('#a_div').mySet();
$('#a_div').myGet(); // outputs 'undefined'
var $other_div = $('#other_div');
$other_div.mySet();
$other_div.myGet(); // outputs 'other_div'
为了实现您想要的目标,您必须将数据持久保存在jQuery对象实例之外的其他地方。 jQuery提供了一种通过.data()
方法执行此操作的方法。 此方法使您可以将数据附加到DOM元素。 检查其文档 。
jQuery.fn.myRealSet = function(){
this.data('myVar', this.attr('id'));
};
jQuery.fn.myRealGet = function(){
console.log(this.data('myVar'));
}
$('#final_div').myRealSet();
$('#final_div').myRealGet(); // outputs 'final_div'
您可以在以下位置测试此代码段: http : //jsfiddle.net/HPjYn/
编辑:我尚无法评论其他人的答案,但是按照建议添加jQuery原型变量将使数据可从任何jQuery对象实例获得,我认为这不是这里的意图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.