最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Same function for multiple jQuery objects - Stack Overflow

programmeradmin0浏览0评论

I want the same functions to run for 2 jQuery objects: $('input[type="text"]') and $('textarea[type=text]'). How can I bine 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 : '');  
        }  
});  

Thanks!

I want the same functions to run for 2 jQuery objects: $('input[type="text"]') and $('textarea[type=text]'). How can I bine 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 : '');  
        }  
});  

Thanks!

Share Improve this question edited Dec 29, 2011 at 18:48 Xavi 20.5k14 gold badges74 silver badges63 bronze badges asked Jan 10, 2010 at 21:21 Espen ArnoyEspen Arnoy 1571 gold badge5 silver badges13 bronze badges 2
  • 1 Why does your textarea have a type=text? That is not a valid attribute for a textarea – Doug Neiner Commented Jan 10, 2010 at 21:26
  • Didn´t know that. My object is now $('textarea') – Espen Arnoy Commented Jan 10, 2010 at 21:34
Add a ment  | 

3 Answers 3

Reset to default 9

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)

  1. 暂无评论