如何让一个JS函数的参数是带有参数的函数名来调用另一个函数?
类似的东西:
onClick="Clicked(this, 'SomeFunction('test')'"
此致
答案 0 :(得分:11)
onClick = "Clicked(this, function () {SomeFunction('test')});"
function Clicked (obj, functionToFire)
{
functionToFire();
}
答案 1 :(得分:2)
<span onclick="Clicked(this, 'SomeFunc', ['test', 123])">AAAA</span>
...
function Clicked(thisObject, funcName, params)
{
// find an object with name funcName in default (window) scope
var func = window[funcName];
// test that the object exist and that it's a function
if (func && typeof func == "function")
{
// call the function with passed params
// passing 'thisObject' enables to use 'this' keyword within the called function
func.apply(thisObject, params);
// as an alternative you may call it without 'this' object
func.apply(null, params);
}
}
function SomeFunc(text, num)
{
alert("text: " + text + ", number: " + num);
}
答案 2 :(得分:1)
<script>
function doSomeWork(arg1, arg2)
{
arg2();
}
function displayThis(msg)
{
alert(msg);
}
doSomeWork("11",function(){ displayThis("123");});
</script>
答案 3 :(得分:-1)
你有什么工作,但是,你需要使用javascript eval函数来评估函数中的值一次:
function Clicked(obj, functionText)
{
// do something with object....
eval(functionText);
}
否则,如果没有参数,您可以随时传递函数:
onClick="Clicked(this, SomeFunction)"
并实现如下:
function Clicked(obj, func)
{
// do something with object...
func();
}
答案 4 :(得分:-1)
这不可能更简单:
onClick = "function() { someFunction('test') }"