2010-12-23 72 views
0

你好,我輸入密碼類型。我想做簡單的事情。如果輸入不在焦點上,則輸入具有默認值。我試圖用jQuery來做到這一點。 我的HTML:jQuery模糊/焦點奇怪的情況

<input type="password" name="password" id="password" defvalue="password" class="filling-password"> 

我的JavaScript(jQuery的):

$('.filling-password').each(function(){ 
    var b = $(this); 
    var id = this.id; 
    var val = b.attr("defvalue"); 
    var textInput = '<input id="'+id+'-text" type="text" value="'+val+'">'; 
    $(textInput).insertAfter(this); 
    b.hide(0); 
    $("#"+id+"-text").focus(function(){ 
     $(this).hide(0); 
     b.show(0).focus(); 
    }); 
    b.blur(function(){ 
     if ($(this).val() == "") { 
      $(textInput).insertAfter(this); 
      b.hide(0); 
     } 
    }); 
}); 

所有工作不錯。但只有一次。當我點擊第一次輸入變空時,當我模糊輸入有默認值。但如果我第三次點擊什麼都沒有發生。哪裏不對?或者也許有更好的方法來做到這一點?
對不起,我的英語。先謝謝你。

回答

1

這裏有一種方法大致像你描述它,裏面插入當然$(function() { ... });live demo):

$('.filling-password').each(function() { 
    var pass = $(this), 
     text = $('<input type="text"/>').val(pass.attr('defvalue')); 

    text.insertBefore(pass).focus(function() { 
     text.hide(); 
     pass.show().focus(); 
    }); 

    pass.hide().blur(function() { 
     if (pass.val() == '') { 
      pass.hide(); 
      text.show(); 
     } 
    }); 
}); 

可能更好的是覆蓋在文本框(live demo)的頂部的標籤:

$('.filling-password').each(function() { 
    var pass = $(this), 
     div = pass.wrap('<div/>').parent(), 
     label = $('<label/>').attr('for', pass.attr('id')).text(pass.attr('defvalue')).prependTo(div); 

    div.css({ 
     display: 'inline', 
     position: 'relative' 
    }); 

    label.css({ 
     color: '#666', 
     fontSize: '12px', 
     position: 'absolute', 
     left: '4px', 
     bottom: '2px' 
    }); 

    pass.focus(function() { 
     label.hide(); 
    }).blur(function() { 
     if(pass.val() == '') { 
      label.show(); 
     } 
    }); 

有一個jQuery plug-in that implements the latter approach更漂亮。

-1

我不知道jQuery的,但判斷你的代碼,這是你想要去的方向:

$('.filling-password').each(function(){ 

    var value = $(this).attr('value'); 
    var defaultvalue = 'password'; 


    $(this).blur(function() { 

     if($(this).val() === '') $(this).value = defaultvalue; 
    }); 


    $(this).focus(function() { 

     if($(this).val() === defaultvalue) $(this).value = ''; 
    }); 
}); 

以及用於在HTML中,利用DefValue屬性是無效的,我相信:

<input type="password" name="password" id="password" value="password" class="filling-password"> 
+0

-1。 1.你不知道jQuery。 2.使用密碼輸入將符號轉換爲「*」。 – pltvs 2010-12-23 17:10:27