2011-04-27 125 views
0

我可以創建一個變量,它是此類型的函數:jQuery的類型函數作爲變量

jQuery.fn.appendValueToTextArea = function(txt){ 
    return this.each(function(){ 
    this.value += txt; 
    }); 
}; 

我試着把var放在它的前面,但是我得到一個錯誤。

+1

困惑。你想var myfunction = function(){}或別的東西? – 2011-04-27 22:03:53

+0

你能澄清你的問題嗎?你試過在前面放一個'var'?你想創建一個_variable_,它是_which_類型的_function_?你的問題沒有意義。 – 2011-04-27 22:03:58

+0

你的代碼似乎做你想做的事:http://jsfiddle.net/L8fSn/ – Matt 2011-04-27 22:05:16

回答

3

如果你想叫一個元素的方法就像你在評論中寫道,你一定要延長jQuery.func

也許你只是想將名稱存儲在變量中?

var name = 'appendValueToTextArea'; 
element[name]('text'); 

唯一的另一種方法是參考存儲的功能和使用.call().apply()

var func = jQuery.fn.appendValueToTextArea = function(txt) { 
    // ... 
}; 

func.call(element, 'text'); 

或(因爲我不知道你真正想要的),您可以將功能分配給先將變量分配給jQuery.fn.appendValueToTextArea

var func = function(txt) { 
    // ... 
}; 

jQuery.fn.appendValueToTextArea = func; 
1
jQuery.fn.appendValueToTextArea = function(txt){ 
    return this.each(function(){ 
    this.value += txt; 
    }); 
}; 

//This would put the function above in a variable. 
//However, I'm not exactly sure what this gains you  
var myfunction = jQuery.fn.appendValueToTextArea; 
2

如果你定義的功能已經被定義的變量後會發生什麼?

jQuery.fn.appendValueToTextArea = function(txt){ 
    return this.each(function(){ 
    this.value += txt; 
    }); 
}; 

var fn = jQuery.fn.appendValueToTextArea;