2011-01-13 32 views
0

对下面的函数进行编码的最有效的方法是什么?如果他们试图提交一个空表单并且还要清除表单以供他们进入,那么这些函数会发出警告。是否有更高效/优化的方式来编写这段jQuery?

$("#newsletter-subscribe").focus(function() { 
     if(this.value=='Your email address'){ 
      this.value=''; 
     } 
    }); 

    $("#newsletter-subscribe").blur(function(){ 
     if(this.value==''){ 
      this.value='Your email address' 
     }; 
    }); 

    $("#subscribe").bind("submit", function(e){ 
     email = $("input#newsletter-subscribe").val(); 
    $("input#newsletter-subscribe").val(email); 
    if(jQuery.trim(email) == 'Your email address' || jQuery.trim(email) == '') { 
     alert('Please enter your email address to subscribe.'); 
     return false; 
    } 

    }); 

回答

3

您可能要查看jQuery Watermark插件。

这个插件让你看起来像水印或工作作为占位表单元素添加默认的文字......在某种程度上,以防止不必要的信息工作是最可能被发送到服务器

+0

这非常适合我所寻找的东西 - 谢谢! – simonyoung 2011-01-13 13:53:40

0

有是更有效地做到这一点的方式。但是你的代码是相当好的。没有循环没有大规模的数据结构。应该没有理由花时间优化它。

1

继承人代码的一块,我在这种情况下使用,会检查HTML5占位符[http://dev.w3.org/html5/spec/Overview.html#the-placeholder-attribute]的支持是avaible,如果不是他提供这

  if(!('placeholder' in document.createElement('input'))){ 
       $('input[type="text"][placeholder] , textarea[placeholder]').each(function(){ 
        if('' != $(this).attr('placeholder')){ 
         if('' == $(this).val() || $(this).attr('placeholder') == $(this).val()){ 
          $(this).val($(this).attr('placeholder')).css('color','gray'); 
         } 
        } 
       }); 
       $('input[type="text"][placeholder], textarea[placeholder]').focus(function(){ 
        if($(this).attr('placeholder') == $(this).val()){ 
         $(this).val(''); 
         $(this).css('color','#272727'); 
        } 
       }).blur(function(){ 
        if('' == $(this).val()){ 
         $(this).css('color','gray').val($(this).attr('placeholder')); 
        } 
       }); 
      } 

所以只写你的元素,如: <input name="foo" type=text" placeholder="Placeholder text" />

相关问题