我今天写了一个表单元素。 当用户点击时,输入中的内容将会被清除。 当鼠标点击其他地方时,输入的值将被保存为输入的值。
像这样的效果
当用户单击时,文本消失。
html代码
jq码
$(document).ready(function(e) {
var temp;
$(":text").focusin(function(){
var value = $(this).val();
if ($(this).val() == "请输入密码" || $(this).val() == "请输入您的邮箱地址" || $(this).val() == "确认密码" || $(this).val() =="请输入用户名") {
if($(this).val() == "确认密码" || $(this).val() == "请输入密码") {
$(this).attr('type','password')
}
$(this).val("")
}
//alert(value)
})
$(":input").focusout(function(event) {
/* Act on the event */
if($(this).val() == "") {
if ($(this).hasClass('pwd')) {
$(this).attr('type','text')
};
$(this).val(temp)
}
});
})
这样以后基本需要的功能就可以实现了jquery 获取input的值,但是代码不够堂堂jquery 获取input的值,所以就想到了用链表来保存值,
var arr_ = [];
var temp;
$(":text").each(function() {
arr_.push($(this).val())
})
$(":text").focusin(function(){
var that = this;
var value = $(that).val();
temp = value;
$.each(arr_,function(i,n) {
if(value==n){
$(that).val("");
if(value=="请输入密码"||value=="确认密码"){
$(that).attr("type","password");
}
}
});
})
我又发现了一个问题,总是需要一个全局变量temp来保存值,这对javascript来说不好,所以我又想到了data属性
$(document).ready(function(e) {
var arr_ = [];
$(":text").each(function() {
arr_.push($(this).val())
})
$(":text").focusin(function(){
var that = this;
var value = $(that).val();
$.each(arr_,function(i,n) {
if(value==n){
$(that).val("");
if(value=="请输入密码"||value=="确认密码"){
$(that).attr("type","password");
}
}
});
})
$(":input").focusout(function(event) {
/* Act on the event */
if($(this).val() == "") {
if ($(this).hasClass('pwd')) {
$(this).attr('type','text')
};
$(this).val($(this).attr("data"));
}
});
})
这看起来会舒服很多。