开发者

Same function for multiple jQuery objects

I want the same functions to run for 2 jQuery objects: $('input[type="text"]') and $('textarea[type=text]'). How can I combine those two in the code below? (currently, only input is included).

$('input[type="text"]').focus(function() {   
        if (this.value == this.defaultValue){  
            this.value = '';  
        }  
        if(this.value != this.defaultValue){  
            this.select();  
        }  
}); 

$('input[type="text"]').blur(function() {    
        if ($.trim(this.value == '')){  
            this.value = (this.defaultValue ? this.defaultValue : '');  
   开发者_Go百科     }  
});  

Thanks!


Try this:

$('textarea[type="text"], input[type="text"]').focus(...).blur(...);

Similarly you can also use jQuery's add function:

$('textarea[type="text"]').add('input[type="text"]').focus(...).blur(...);


May be easier to put a class on it and filter by that.


You could create a plugin:

jQuery.fn.clearDefValueOnFocus = function() {
    return this.focus(function(){
        if (this.value == this.defaultValue){  
            this.value = '';  
        }  
        if(this.value != this.defaultValue){  
            this.select();  
        }  
    }).blur(function(){
        if (jQuery.trim(this.value) == ''){  
            this.value = this.defaultValue || '';  
        }  
    });
};

$('input[type="text"]').clearDefValueOnFocus();
$('textarea[type=text]').clearDefValueOnFocus();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜