jquery动态函数

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

问题:

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

例:

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

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

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

解决方法

你想动态调用foo或bar?

function callMethod(method)
{
     method();
}

callMethod(foo); // foo is the symbol for your method
callMethod(bar); // etc

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

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

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

var methodName = 'foo';
var text = 'This is ' + methodName; // This is foo
var method = eval('(' + methodName + ')');
method(); // calls foo()

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...