微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐