[英]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.