jquery实现form表单赋默认值【以时间为例】

$(function() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    //时间格式为YY-MM-DD HH:mm:ss
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    $('#inittime').val(currentdate);//引号内为input的id
    $('#inittime').focus(function() {
        //获得焦点时,如果值为默认值,则设置为空
        if ($(this).val() == currentdate) {
            $(this).val("");
        }
    });
    $('#inittime').blur(function() {
        //失去焦点时,如果值为空,则设置为默认值
        if ($(this).val()== "") {
            $(this).val(currentdate);
        }
    });
});
 
 

      

$(function(){});里的代码是在页面内容都加载完才执行的,如果把代码直接写到script标签里,

当页面加载完这个script标签就会执行里边的代码了,此时如果标签里执行的代码调用了当前还没加载过来

的代码或者dom,那么就会报错,当然如果把script标签放到页面最后面那么就没问题了,此时和ready效

果一样。


 

猜你喜欢

转载自blog.csdn.net/qq_38377613/article/details/81017803