前端JS/JQuery常用封装的方法介绍

1. 获取长度为len的随机字符串
function getRandomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;

}

2. 自动获取页面所有的表单数据,并转换成json对象
function transfer(formId) {
    var jsonuserinfo = $('#' + formId).serializeObject();
    return jsonuserinfo;
}
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

3.  清空所有表单数据
function clearForm(formId) {
    $("#" + formId).find('input, textarea').each(function () {
        $(this).val("");
    });
}

4. 获取站点根目录
function getBasePath() {
    var obj = window.location;
    var contextPath = obj.pathname.split("/")[1];
    var basePath = /*obj.protocol+"//"+obj.host+*/"/" + contextPath;
    return basePath;
}

5. 对一些不能为空的form标签进行判断,需要给定要判断的form标签一个class为check的名字
$(".check").on("blur", function () {
    if ($(this).val() == "" || $(this).val() == null || $(this).val() == undefined) {
        $(this).css("border-color", "red");
        $(this).prop("placeholder", "不能为空!");
    } else {
        $(this).css("border-color", "");
    }
})

6. 

猜你喜欢

转载自blog.csdn.net/richangbiji/article/details/77587821