在准备好的处理程序中使用字符串调用函数...不起作用

Calling a function using a string within a ready handler... doesn't work

所以你想执行一个名字在字符串或变量中的函数:

var fn = "foobar";

function foobar() {
    console.log('say something');
}

这样的回答 - How to execute a JavaScript function when I have its name as a string - 说要这样做:

window[fn](); // outputs 'say something'

但是... 这个 由于某些原因不起作用:

jQuery(document).ready(function($){
    var fn = "foobar";

    function foobar() {
        console.log('say something');
    }

    window[fn](); // undefined
});

这个有效,但是:

jQuery(document).ready(function($){
    var fn = "foobar";

    window[fn](); // outputs 'say something'
});

/* I'm outside the ready handler */

function foobar() {
    console.log('say something');
}

我想将我的函数保留在那个准备好的处理程序中,这样我就不必编写一堆匿名函数来将 jQuery 定义为 $。我该怎么做?


更新

这是我想要做的事情:

<div data-control="toggleNext">FAQ</div>
<div>Here's some text that will be hidden until toggled</div>

JS:

jQuery(document).ready(function($){

    function toggleNext() {
        // add ".js_toggled" to .next() element
    }

    $('[data-control]').each(function(){
        var fn = window[$(this).data('control')]; // <-- this don't werk
        if (typeof fn === 'function') fn(this);
    });

});

如果您的函数在就绪处理程序中,它将无法在 window 上使用,除非您专门如此设置。但是,无论如何这都是个坏主意,只需离开 window 并在您的文档就绪块中定义您自己的本地对象。

jQuery(document).ready(function($){
    var fn = "foobar", methods = {};
    methods[fn] = function () {
        console.log('say something');
    }
    $('[data-control]').each(function(){
        var fn = methods[$(this).data('control')];
        if (typeof fn === 'function') fn(this);
    });
    //methods[fn](); 
});

@KevinB 让我找到了答案,我会让他接受,但我认为这值得写出来,因为我想其他人也会想做这样的事情。

由于window对象不包含ready handler内部声明的函数(即没有显式调用window['functionName'] = function() {...}),你可以定义一个局部对象并调用它:

HTML:

<div data-control="toggleNext">FAQ</div>
<div>Here's some text that will be hidden until toggled</div>

JS:

jQuery(document).ready(function($){

    var myFuncs = {

        toggleNext : function(me) {
            // add ".js_toggled" to $(me).next() element
        },

        doSomethingCool : function() {
            // you'd better make it good
        }
    }

    $('[data-control]').each(function(){

        var funcName = $(this).data('control'),
            fn = myFuncs[funcName];
        if (typeof fn === 'function')
            fn(this);

    });

});

我不知道,我是唯一觉得有用的人吗?