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.
- 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
3 Answers
Reset to default 3If 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
版权声明:本文标题:javascript - jQuery type function as a variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742063455a2418691.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论