简体   繁体   English

通过string调用jQuery定义的函数

[英]Call jQuery defined function via string

I'd like to call functions I've defined within the document ready function of jQuery, but am having a bit of trouble. 我想调用我在jQuery的文档就绪函数中定义的函数,但是遇到了一些麻烦。 I have the following code: 我有以下代码:

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. 我不想使用evalwindow[fn]似乎不起作用。 The two test functions don't appear to be indices in the window variable. 两个测试函数似乎不是窗口变量中的索引。 I appreciate the help and knowledge. 我很感激帮助和知识。

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 handler函数中作用域:

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: 或者,您可以将函数移动到全局范围,以便它们自动注册到窗口对象,如下所示:

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]();
    }

});

如果不是Eval,最好的方法是使用零毫秒的setTimeout,因为您可以将函数指定为字符串。

setTimeout('myfunction()',0,);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM