2011-01-13 65 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" />

相關問題