javascript 通过字符串调用jQuery定义的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7424476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call jQuery defined function via string
提问by Evan
I'd like to call functions I've defined within the document ready function of jQuery, but am having a bit of trouble. I have the following code:
我想调用我在 jQuery 的文档就绪函数中定义的函数,但遇到了一些麻烦。我有以下代码:
jQuery(document).ready( function($) {
function test1() {
alert('test1');
}
function test2() {
alert('test2');
}
var test_call = '2';
var fn = 'test' + test_call;
// use fn to call test2
});
I don't want to use eval
, and window[fn]
doesn't seem to be working. The two test functions don't appear to be indices in the window variable. I appreciate the help and knowledge.
我不想使用eval
,而且window[fn]
似乎不起作用。这两个测试函数似乎不是 window 变量中的索引。我感谢帮助和知识。
回答by jfriend00
All I can think of that doesn't use eval()
or some form of eval (passing a string to setTimeout()
is a form of eval()
), is to register the relevant function names on an object and then look up the function name on that object:
我能想到的所有不使用eval()
或某种形式的 eval(将字符串传递给setTimeout()
是一种形式eval()
),就是在对象上注册相关的函数名称,然后在该对象上查找函数名称:
jQuery(document).ready( function($) {
function test1() {
alert('test1');
}
function test2() {
alert('test2');
}
// register functions on an object
var funcList = {};
funcList["test1"] = test1;
funcList["test2"] = test2;
var test_call = '2';
var fn = 'test' + test_call;
if (fn in funcList) {
funcList[fn]();
}
});
or the registration could be done in the definition of the functions. If they were global functions, they would be implicitly registered on the window
object, but these are not global as they are scoped inside the document.ready handler function:
或者注册可以在功能定义中完成。如果它们是全局函数,它们将被隐式注册到window
对象上,但它们不是全局的,因为它们的作用域在 document.ready 处理函数中:
jQuery(document).ready( function($) {
var funcList = {};
funcList.test1 = function test1() {
alert('test1');
}
funcList.test2 = function test2() {
alert('test2');
}
var test_call = '2';
var fn = 'test' + test_call;
if (fn in funcList) {
funcList[fn]();
}
});
Or, you could move the functions to the global scope so they are automatically registered with the window object like this:
或者,您可以将函数移动到全局范围,以便它们自动注册到 window 对象,如下所示:
function test1() {
alert('test1');
}
function test2() {
alert('test2');
}
jQuery(document).ready( function($) {
var test_call = '2';
var fn = 'test' + test_call;
if (fn in window) {
window[fn]();
}
});
回答by andy
The best way, if not Eval, would be to use setTimeout with zero milliseconds, as you can specify the function as a string.
如果不是 Eval,最好的方法是使用零毫秒的 setTimeout,因为您可以将函数指定为字符串。
setTimeout('myfunction()',0,);