2010-10-08 157 views
1

我试图让所有textareas删除焦点上的默认文本,除了类的“预填充”。 但问题是“预填充”类的textareas仍在被选中和包括在内。jQuery .not()方法无法正常工作

有关如何解决此问题的建议? 谢谢。

jQuery(document).ready(function inputHide(){ 

    $('textarea, input:text, input:password').not($('.pre-fill')).focus(function() { 
      if ($(this).val() === $(this).attr('defaultValue')) { 
       $(this).val(''); 
      } 
     }).blur(function() { 
      if ($(this).val()==='') { 
       $(this).val($(this).attr('defaultValue')) 
      } 
     }); 

}); 

回答

5

你不应该有.not方法调用中jQuery的变量($)。试试这个:

.not('.pre-fill') 

在你的代码的情况下:

$('textarea, input:text, input:password').not('.pre-fill').focus(function() { 
     if ($(this).val() === $(this).attr('defaultValue')) { 
      $(this).val(''); 
     } 
    }).blur(function() { 
     if ($(this).val()==='') { 
      $(this).val($(this).attr('defaultValue')) 
     } 
    }); 
+2

'this.value'比'$(this).val()'效率更高,因为您不必首先创建jQuery对象,然后调用jQuery方法。 – 2010-10-08 22:55:23

1

您还可以使用:not() selector

请注意,this.value$(this).val()效率更高,因为它是直接访问DOM元素的属性,而不是通过先构建jQuery对象然后调用jQuery方法来访问完全相同的属性。

$('textarea, input:text:not(.pre-fill), input:password:not(.pre-fill)') 
    .focus(function() {   
     if (this.value === $(this).attr('defaultValue')) { 
      this.value = ""; 
     } 
    }).blur(function() { 
     if (this.value === '') { 
      this.value = $(this).attr('defaultValue'); 
     } 
    });