admin管理员组文章数量:1424893
i want to run a function, inside another function dynamically...
let say :
<script>
var x = function(r,s){
r(s);
}
var a = function(item){
alert("aA");
}
var b = function(item){
alert("bB");
}
</script>
is this possible? i take "r" from function x's argument as a function name, and i want to run it.
if r=a, then it will trigger function a()
and if r=b, function b triggered instead...
how could i do that?
i want to run a function, inside another function dynamically...
let say :
<script>
var x = function(r,s){
r(s);
}
var a = function(item){
alert("aA");
}
var b = function(item){
alert("bB");
}
</script>
is this possible? i take "r" from function x's argument as a function name, and i want to run it.
if r=a, then it will trigger function a()
and if r=b, function b triggered instead...
how could i do that?
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Sep 5, 2013 at 4:34 dwerty_weirddwerty_weird 1934 silver badges17 bronze badges 3- 3 whats wrong with your try above? – RienNeVaPlu͢s Commented Sep 5, 2013 at 4:37
- 1 what you have is working fine. what's wrong with it? – Praveen Lobo Commented Sep 5, 2013 at 4:45
- sorry, i just wrote it without proper test. it actually , working,.. huhuhu ty.. :D – dwerty_weird Commented Sep 5, 2013 at 7:21
3 Answers
Reset to default 5You could simply test r
and call each function as needed.
if (r === 'a') {
a(s);
} else if (r === 'b') {
b(s);
}
Or, if you have many functions for this or don't always know them all ahead of time, you can organize them in an Object
and use bracket operators to treat r
as a key name to access them:
var mands = {
a: function(item){
alert("aA");
},
b: function(item){
alert("bB");
}
};
var x = function (r, s) {
var mand = mands[r];
if (typeof mand === 'function') {
mand(s);
}
};
x('a', 'foo'); // alerts `aA`
Or, even just pass a
and b
as the arguments themselves with your current definition of x()
.
x(a, 'foo'); // calls `a` as `r`, passing 'foo' along
By passing the name of the function as the first parameter to x when calling it.
x(a, {}); // alert("aA");
x(b, {}); // alert("bB");
Note that you're passing the reference to the function, not a string. This is because functions in JavaScript are objects and are passed by reference, not by value. So var a = function() {...};
actually means that variable a holds a reference to the function.
you mean like:
var x = function(r,s){
window[r](s);
}
var a = function(item){
alert("aA");
}
var b = function(item){
alert("bB:" + item);
}
x('b', 'test');
本文标签:
版权声明:本文标题:jquery - How to trigger javascript function, inside a javascript function, by function's argument? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745430702a2658311.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论