2010-12-23 74 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