2012-12-20 30 views
0

我有一個問題,當我分離當前的焦點元素,並再次插入使用Tab鍵移動字段。請在jsfiddle.找到我的代碼。另見下文:問題與焦點()後detach和insertBefore

JS代碼:

$(document).ready(function() { 
    $('.formElem').focusin(function() { 
     // Remove default text on focus in 
     if ($(this).val() == $(this).attr('title')) { 
      $(this).val('').removeClass('defaultText'); 
      if (($(this).attr('id') == 'reg_pwd') || ($(this).attr('id') == 'reg_conf_pwd')) { 
       id = '#' + $(this).attr('id'); 
       marker = $('<span>123</span>').insertBefore($(this)); 
       $(this).detach().attr('type', 'password').insertAfter(marker); 
       marker.remove(); 

      } 
      if ($(this).get(0) != $(':focus').get(0)) { 
       $(this).focus(); 
      } 
     } 
    }).focusout(function() { 
     // Remove default text on focus out 
     if ($(this).val() === '') { 
      $(this).val($(this).attr('title')).addClass('defaultText'); 
      if (($(this).attr('id') == 'reg_pwd') || ($(this).attr('id') == 'reg_conf_pwd')) { 
       marker = $('<span>123</span>').insertBefore($(this)); 
       $(this).detach().attr('type', 'text').insertAfter(marker); 
       marker.remove(); 
      } 
     } 
    }); 
});​ 

代碼從文本改變字段的類型密碼和來回。當您單擊或使用Tab鍵到達密碼字段時,它會在重新添加後失去焦點。謝謝如果有人可以找出原因。

+0

我只是在JSFiddle中迷惑同樣的事情。 HTML5佔位符屬性是否不解決這種類型代碼的需求? –

+0

目前還不清楚他想要用123跨度做什麼。此外,一些瀏覽器(即MSIE)在創建後不會讓您更改輸入的類型。 – Alnitak

+0

跨度充當重新插入元素的標記。我沒有研究過MSIE,只是探索這種技術。 – Pradeep

回答

0

看起來您使用的是html5,所以也許您可以利用placeholder屬性。而不是<input value="blah" />使用<input placeholder="blah" />。現在你甚至不需要有defaultText類,所以你可以刪除它,以及你有相關的jQuery代碼,它們會刪除和添加類。

現在您還可以將<input type="text" />更改爲<input type="password" />作爲密碼字段。我不確定你想用<span>123</span>做什麼。或許,我不完全理解你的問題。但下面似乎完成了你想要做的效果。

一個的jsfiddle以及http://jsfiddle.net/8BBRC/2

編輯:得到錯誤的jsfiddle鏈接。

<input type="text" class="formElem" id="reg_fullname" name="fullname" placeholder="Full Name" title="Full Name" /><br /> 
<input type="email" class="formElem" id="reg_email" name="email" placeholder="Email Address" title="Email Address" /><br /> 
<input type="password" class="formElem" id="reg_pwd" name="pwd" placeholder="Confirm" title="Password" /><br /> 
<input type="password" class="formElem" id="reg_conf_pwd" name="conf_pwd" placeholder="Confirm Password" title="Confirm Password" /><br /> 
<input type="submit" id="reg_submit" value="Submit" /><br />