【问题标题】:jQuery plugin, return value from functionjQuery插件,从函数返回值
【发布时间】:2011-02-06 18:11:52
【问题描述】:

标记:

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

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

【问题讨论】:

  • 调用 $(this).validate($(this).attr('name')) ?另外,使用 $(this).val() 而不是 this.val()。

标签: javascript jquery function types


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 2015-05-25
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    相关资源
    最近更新 更多