javascript - jQuery 插件,从函数返回值

标签 javascript jquery function types

标记:

<input type="text" name="email" />

代码:

$(':text').focusout(function(){
    $(this).validate(function(){
        $(this).attr('name');
    });
});

插件:

(function($){  
    $.fn.validate = function(type) {  
        return this.each(function(type) {  
            if (type == 'email') {
                matches = this.val().match('/.+@.+\..{2,7}/');
                (matches != null) ? alert('valid') : alert('invalid');
            }
            /*else if (type == 'name') {

            }
            else if (type == 'age') {

            }
            else if (type == 'text') {

            }*/
            else {
                alert('total failure');
            }
        });
    };  
})(jQuery);

问题是当我执行上面的代码时,它运行插件就像类型是一个字符串一样:“function(){ $(this).attr('名字'); });"而不是将其作为函数执行。我该如何解决这个问题?

最佳答案

您必须检查参数是否为函数。如果是,则使用返回值,否则假定它是文字值。

(function($) {
    $.fn.validate = function(type) {
        //check if type type is a function else take it as literal
        type = typeof type !== "function" ? type : type();
        return this.each(function(type) {
            ...
        });
    };
})(jQuery);

关于javascript - jQuery 插件,从函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2617942/

相关文章:

javascript - 尝试镜像使用stradown.js 的站点

javascript - 如果语句未注册

javascript - 通过 Javascript 验证表单字段

jquery - 在 jira 中使用 jQuery

javascript - 如何在 Javascript 的单行函数中返回值?

Python.比较两个列表中的数字并找到最大值

javascript - 如何在表单提交时更改不显示以阻止

Javascript:何时使用 forEach 而不是 map 的具体示例?

c - 在每个 C 函数的开头自动运行代码

javascript - Promise的用法。递归中的所有操作似乎都不起作用