开发者

jQuery plugin, return value from function

开发者 https://www.devze.com 2022-12-26 04:34 出处:网络
Markup: <input type=\"text\" name=\"email\" /> Code: $(\':text\').focusout(function(){ $(this).validate(function(){

Markup:

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

Code:

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

Plugin:

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

The problem is that when I execute the code above, it runs the plugin as if type was a string: "function(){ $(this).attr('name'); });" instead of executing it as a function. How do I solve this?


You must check if the parameter is a function. If yes use the return value else assume it's a literal value.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号