admin管理员组

文章数量:1320660

can I create a variable that is a function of this type:

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

?

I tried putting a var in front of it but I get a error.

can I create a variable that is a function of this type:

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

?

I tried putting a var in front of it but I get a error.

Share Improve this question asked Apr 27, 2011 at 22:00 AlexAlex 68.1k185 gold badges459 silver badges650 bronze badges 5
  • 1 confused. do you want var myfunction = function() {} or something else? – John Hartsock Commented Apr 27, 2011 at 22:03
  • Could you clarify your question? You tried putting a var in front of what? You want to create a variable that is a function of which type? Your question doesn't make sense. – Matt Ball Commented Apr 27, 2011 at 22:03
  • Your code seems to do what you're trying to do: jsfiddle/L8fSn – Matt Commented Apr 27, 2011 at 22:05
  • well jquery functions can be called like this: element.appendValueToTextArea('sometext') I want to create a function that can be called like that, but I want the function to be a variable, like the one John posted above – Alex Commented Apr 27, 2011 at 22:05
  • I also am here to vote confused. Can you give an example of a function that you would describe as "a variable"? – Pointy Commented Apr 27, 2011 at 22:07
Add a ment  | 

3 Answers 3

Reset to default 3

If you want to call a method on an element like you wrote in the ment, you definitely have to extend jQuery.func.

Maybe you just want to store the name in a variable?

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

The only other way is to store a reference to the function and use .call() or .apply():

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

func.call(element, 'text');

Or (as I am not sure what you really want) you can assign the function to a variable first and then assign it to jQuery.fn.appendValueToTextArea:

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

jQuery.fn.appendValueToTextArea = func;

What happens if you define the variable after the function has been defined?

i.e.

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

var fn = jQuery.fn.appendValueToTextArea;
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;

本文标签: javascriptjQuery type function as a variableStack Overflow