jquery动态函数

Phi*_*ord 3 jquery dynamic

我只需要逻辑和理解我如何做到这一点.

问题:

我有几个非常相似的功能,但我想动态创建/调用

例:

$(document).ready(function() {         
    function foo() {
        $("#foo_elem").toggle(true).attr('required', true);
        alert('This is foo');
    }

    function bar() {
        $("#bar_elem").toggle(true).attr('required', true);
        alert('This is bar');
    }
});
Run Code Online (Sandbox Code Playgroud)

如何传入foo/bar来创建函数?伪代码

$(document).ready(function() { 
    // would pass foo/bar to this?        
    $($x)(function() {
        $("#"+$(this)+"_elem").toggle(true).attr('required', true);
        alert('This is '+$(this));
    });
});
Run Code Online (Sandbox Code Playgroud)

Tej*_*ejs 9

你想动态调用foo或bar?

function callMethod(method)
{
     method();
}

callMethod(foo); // foo is the symbol for your method
callMethod(bar); // etc
Run Code Online (Sandbox Code Playgroud)

在很高的水平.但是,在您的实例中,您要求将该符号用作选择器中的变量:

function callMethod(elementPrefix)
{
    $('#' + elementPrefix+ '_elem').toggle(true).attr('required', true);
    alert('This is ' + elementPrefix);
}
Run Code Online (Sandbox Code Playgroud)

如果要将其用作字符串值和方法名称,则可以使用符号来获取方法:

var methodName = 'foo';
var text = 'This is ' + methodName; // This is foo
var method = eval('(' + methodName + ')');
method(); // calls foo()
Run Code Online (Sandbox Code Playgroud)