在JQuery函数中保存本地数据

Saving a local data in a JQuery function

本文关键字:数据 保存 JQuery 函数      更新时间:2023-09-26

我想创建两个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;
}

当你运行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/

EDIT:我还不能评论其他人的答案,但是按照建议添加一个jQuery原型变量将使数据从任何jQuery对象实例中可用,我不认为这是这里的目的。

你可以在全局范围内创建一个命名空间:

window.yourNamespace = {};

,然后把你的varList变量放在命名空间中:

yourNamespace.varList = []; //Whatever you want here

这样,变量将可用于您的两个函数(或任何函数)。

您对this的理解在我看来有点错误(请原谅,您可能比我更有经验)!this指向函数的调用者。两次都是div main_div。尝试使用在两个函数之外声明的全局变量,或者在第一个函数中使用div上的data属性,并在第二个函数中访问该值。