2011-04-27 83 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;