2011-05-09 39 views
7

我正在嘗試將可見文本添加到說「輸入密碼」的密碼字段中,並且在單擊該文本時清除並鍵入點。我有兩個輸入類型=文本和另一個密碼。密碼輸入在開始時隱藏,但在用「輸入密碼」指令單擊輸入後出現。如果密碼字段爲空,則爲jquery

它這樣做http://mudge.github.com/jquery_example/但我試圖使它的密碼字段。

HTML

<input type="text" id="password_instructions" /> 
<input type="password" id="password" /> 

jQuery的

 var $password = $('#password'); 
     $password.hide(); //hide input with type=password 

     $("#password_instructions").click(function() { 
       $(this).hide(); 
       $('#password').show(); 
       $('#password').focus(); 

       if ($password.val().length === 0) { //if password field is empty    
        $password.focusout(function() { //when clicking outside empty password input 
         $(this).hide(); 
         $('#password_default_value').show(); 
         $('#password_instructions').default_value('Enter a password'); //will clear on click 
        });      
       } 
     }); 

什麼不起作用:

當您填寫的密碼輸入(用點顯示),然後單擊出來的輸入是隱藏的, #password_instruction輸入顯示。所以它不尊重if語句。由於某種原因,即使我輸入了密碼,它仍將輸入視爲空。

我在這裏做錯了什麼?

+0

你使用的是什麼版本的jQuery? – 2011-05-09 19:50:28

+0

最新的一個。爲什麼? – CyberJunkie 2011-05-09 19:51:42

+0

嗯,我以爲我在新的版本中讀了一些關於'.val()'的內容,但它是關於'.attr()'的。別擔心。 :) – 2011-05-09 19:53:15

回答

9

您似乎預計在撥打focus()之後會出現某種「暫停」,並且只有當最終用戶輸入完密碼後纔會執行JS代碼的剩餘部分。

這是不正確的。該功能一次完全執行。

您需要移動下面這段

 if ($password.val().length === 0) { //if password field is empty    
      $password.focusout(function() { //when clicking outside password input 
       $(this).hide(); 
       $('#password_default_value').show(); 
       $('#password_instructions').default_value('Enter a password'); //will clear on click 
      });      
     } 

另一獨立功能:

$('#password').focusout(function() { 
    if ($(this).val().length === 0) { //if password field is empty    
     $(this).hide(); 
     $('#password_default_value').show(); 
     $('#password_instructions').default_value('Enter a password'); //will clear on click 
    } 
}); 
+0

謝謝你的解釋!也許我會將代碼與php關聯得太多。 :) – CyberJunkie 2011-05-09 20:03:09

+0

不客氣。 – BalusC 2011-05-09 20:03:51

3

你的意思是:

<input type="password" placeholder="enter password"> 

如果你想爲腿做到這一點acy瀏覽器,您必須將支票移至onBlur事件。在jQuery中,這看起來像:

$('#password').blur(function() { 
    if ($password.val().length === 0) { //if password field is empty    
     $password.focusout(function() { //when clicking outside password input 
      $(this).hide(); 
      $('#password_default_value').show(); 
      $('#password_instructions').default_value('Enter a password'); //will clear on click 
     });      
    } 
}); 
+1

謝謝!該代碼是佔位符的替代品,我發現這對於Explorer無效:( – CyberJunkie 2011-05-09 19:56:30

+0

啊,很有道理。很多人似乎並沒有意識到佔位符,所以想我最好讓你知道! – 2011-05-09 19:57:47

+0

謝謝!我只是在前面的問題中發現它:)但像往常一樣,瀏覽器使它幾乎無足輕重..人們應該受到教育,以停止使用瀏覽器 – CyberJunkie 2011-05-09 20:00:50

相關問題