多的jQuery的功能相同对象
问题描述:
我想同样的功能,为2名jQuery的对象上运行:$('input[type="text"]')
和$('textarea[type=text]')
。我怎样才能在下面的代码中结合这两个? (目前只包括输入)。多的jQuery的功能相同对象
$('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 : '');
}
});
谢谢!
答
试试这个:
$('textarea[type="text"], input[type="text"]').focus(...).blur(...);
同样你也可以使用jQuery的add
功能:
$('textarea[type="text"]').add('input[type="text"]').focus(...).blur(...);
+0
谢谢! .add方式对我来说效果最好。 – 2010-01-10 21:33:15
答
可能更容易通过把一个类上它和过滤器。
答
您可以创建一个插件:
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();
为什么你的'textarea'有'类型= text'?这是不是一个'textarea' – 2010-01-10 21:26:33
Didn't知道,一个有效的属性。我的目标现在是$(“文本区域”) – 2010-01-10 21:34:40