JS 自定义代码库(持续更新)

19 篇文章 0 订阅
13 篇文章 0 订阅

以下代码是在实践中常用到的,所以将其抽取出来,以下代码皆为原创(除已标注的地方),如有雷同,请联系我(188 2649 5458)。将进行持续维护和更新,有些代码会不定期更改,恕不另行通知。


本作品采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可。


自定义类

StringBuilder

作用:string拼接效率

//自定义Stringbuilder类
function StringBuilder() {
    this.data = new Array();
}
StringBuilder.prototype = {
    append: function () {
        this.data.push(arguments[0]);
    },//添加
    remove:function(start,length){
        this.data.splice(start, length);
    },//删除
    clear: function () {
        this.remove(0, this.data.length);
    },//清空
    get: function (index) {
        return this.data[index];
    },//获取,index or name
    set: function (index,value) {
        this.data[index] = value;
    },
    join: function (separator) {
        return this.data.join(separator || '');
    },//拼接
    toString: function () {
        return this.join();
    }
}




自定义js方法

串行化

作用:某个Container下input的串行化,jQuery.fn下:
            toSerialize: function () {
                var traditional = [];
                $(":input", $(this)).not(":button, :submit, :reset").each(function () {
                    traditional[traditional.length] = {
                        name: this.name||this.id,
                        value: this.value,
                    }
                });
                return jQuery.param(traditional);
            },

查询cookie

查询cookie

        function getCookie(name) {
            return unescape(document.cookie.match(new RegExp(name + '=([^;]+)'))[1]) || undefined;
        }

设置cookie

function setCookie(name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = name + "=" + escape(value) + ((!!expiredays) ? '' : '; expires=' + exdate.toGMTString());
}
当过期日expiredays为负数的时候,即可以清空相应的cookie

表单校验

必填部分

作用:检查表单中required="required"的input
checkFormRequired: function ($checkForm) {
                var $requiredParams = $('[required="required"]', $checkForm);
                for (var i = 0, $elem; !!($elem = $($requiredParams[i])).length; i++) {
                    $elem.prev().children('.error').remove();
                    if (!($.trim($elem.val()))) {
                        $elem.next().css('visibility', 'visible');
                        $elem.focus();
                        $elem.change(function () {
                            $elem.next().css('visibility', 'hidden');
                        });
                        return false;
                    }
                }
                return true;
            }

正则校验

作用:检查表单中data-regex=正则式的输入框
checkFormRegex: function ($checkForm) {
                var $requiredParams = $('[data-regex]', $checkForm);
                for (var i = 0, $elem; !!($elem = $($requiredParams[i])).length; i++) {
                    $elem.prev().children('.error').remove();
                    if (!(new RegExp($elem.attr('data-regex'))).test($.trim($elem.val()))) {
                        $elem.next().css('visibility', 'visible');
                        $elem.focus();
                        $elem.change(function () {
                            $elem.next().css('visibility', 'hidden');
                        });
                        return false;
                    }
                }
                return true;
            }

重置表单

作用,将表单清空
            resetFormData: function ($targetForm) {
                $(":input", $targetForm).not(":button, :submit, :reset, :hidden").val("").removeAttr("checked").remove("selected");
            },


ajax的再次封装

作用:将ajax整个交互过程,错误提示,页面锁定都封装成一个函数
可以直接使用$.ajaxFormModule(options),模块(module)化对象
            ajaxFormModule: function (option) {
                ajaxForm(option.$srcBtn || $(), option.$srcForm || $(), option.method, option.extraData, option.errorTips, option.targetUrl, option.successFunc, option.checkFail, option.isContainImg);
            },
也可以这样合并参数:
options = $.extend({}, $.fn.wysiwyg.defaults, userOptions);
以上方法来自bootstrap-wysiwyg.js

也可以直接使用该方法:
<span style="white-space:pre">	</span>var $backdrop = $('#backdrop');//锁定背景Container         
<span style="white-space:pre">	</span>function ajaxForm($srcBtn, $srcForm, method, extraData, errorTips, targetUrl, successFunc, checkFail, isContainImg,isCheckRegex) {
            $srcBtn = $srcBtn || $();
            $srcForm = $srcForm || $();
            if (($.checkFormRequired($srcForm)&&(!isCheckRegex||(!!isCheckRegex&&$.checkFormRegex($srcForm))))) {
                //必填的部分已经全部填完
                $backdrop.fadeIn();
                $srcBtn.attr('disabled', 'disabled');
                if (isContainImg === true) {
                    //包括图片上传
                    $srcForm.ajaxSubmit({
                        url: targetUrl,
                        type: method || 'POST',
                        success: function (data) {
                            successFunc(data);
                            $srcBtn.removeAttr('disabled');
                            $backdrop.fadeOut();
                        },
                        error: function () {
                            ajaxFail(jqXHR, textStatus + $srcBtn[0].name, errorThrown);
                            $srcBtn.removeAttr('disabled');
                            $backdrop.fadeOut();
                        },
                    });
                }
                else {
                    //仅文字
                    $.ajax({
                        cache: true,
                        type: method || 'POST',
                        url: targetUrl,
                        data: $srcForm.toSerialize().trim().replace(/\+{1,}/g, '%20').replace(/\'/g, "\\'") + extraData,
                    }).done(function (data) {
                        successFunc(data);
                        $srcBtn.removeAttr('disabled');
                        $backdrop.fadeOut();
                    }).fail(function (jqXHR, textStatus, errorThrown) {
                        ajaxFail(jqXHR, textStatus + $srcBtn[0].name, errorThrown);
                        $srcBtn.removeAttr('disabled');
                        $backdrop.fadeOut();
                    });
                }
            } else {
                if ($.isFunction(checkFail)) {
                    checkFail();
                }
            }
        }
//html代码
    <div class="backdrop" id="backdrop" style="display:none;">
        <div class='loader loader--audioWave'></div>
    </div>
//CSS代码
.backdrop {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    background-color: #000;
    height: 100%;
    width: 100%;
    z-index: 10000;
    opacity: .5;
    filter: alpha(opacity=50);
}

.loader--audioWave {
    width: 3em;
    height: 100%;
    background: linear-gradient(#BBB, #BBB) 0 50%, linear-gradient(#BBB,#BBB) 0.625em 50%, linear-gradient(#BBB,#BBB) 1.25em 50%, linear-gradient(#BBB,#BBB) 1.875em 50%, linear-gradient(#BBB,#BBB) 2.5em 50%;
    background-repeat: no-repeat;
    background-size: 0.5em 0.25em, 0.5em 0.25em, 0.5em 0.25em, 0.5em 0.25em, 0.5em 0.25em;
    font-size: 8rem;
    -webkit-animation: audioWave 1.5s linear infinite;
    animation: audioWave 1.5s linear infinite;
    margin: 0 auto;
}

@-webkit-keyframes audioWave {
    25% {
        background-size: .5em 1.5em, 0.5em 0.25em, 0.5em 0.25em, 0.5em 0.25em, 0.5em 0.25em;
    }

    37.5% {
        background-size: 0.5em 0.25em, .5em 1.5em, 0.5em 0.25em, 0.5em 0.25em, 0.5em 0.25em;
    }

    50% {
        background-size: 0.5em 0.25em, 0.5em 0.25em, .5em 1.5em, 0.5em 0.25em, 0.5em 0.25em;
    }

    62.5% {
        background-size: 0.5em 0.25em, 0.5em 0.25em, 0.5em 0.25em, .5em 1.5em, 0.5em 0.25em;
    }

    75% {
        background-size: 0.5em 0.25em, 0.5em 0.25em, 0.5em 0.25em, 0.5em 0.25em, .5em 1.5em;
    }
}//兼容性代码,请自行补充


ajax加载页面,更改URL

concept Version,还没有实验过
点击a时,return false
$('a', $container).click(function () {
    if (!!window.history.pushState) {
        $.ajax(url+href).done(function (result) {
            result=eval('('+ result +')');
            $content.html(result.html);
            window.history.pushState(result.options,result.$(this).attr('href'));
        }).fail(function () {
            return true;
        });
        return false;
    }
    return true;
});

退后或前进时
window.onpopstate = function (event) {
    if (!!event.state && !!event.state.id) {
        $.ajax(options).done(function (result) {
            $content.html(result.html);
        }).fail(function () {

        });
    }
};

无需上传即上传即显示图片

方法一:采用bootstrap-wysiwyg.js的方法,不兼容IE10以下
insertFiles = function (files) {
	editor.focus();
	$.each(files, function (idx, fileInfo) {
		if (/^image\//.test(fileInfo.type)) {
			$.when(readFileIntoDataUrl(fileInfo)).done(function (dataUrl) {
				execCommand('insertimage', dataUrl);
			});
		}
	});
}

方法二:自定方法,兼容IE8+
        function submitImg(inputFile) {//inputFile 为input element
            var files = inputFile.files;
            if (typeof files !== "undefined") {
                var file = files[0];
                if (typeof FileReader !== "undefined" && (/image/i).test(file.type)) {
                    reader = new FileReader();
                    reader.onload = (function () {
                        return function (evt) {
                            showMessage('<img src="' + evt.target.result + '"/>');
                        };
                    }());
                    reader.readAsDataURL(file);
                }
            }
            else {
                inputFile.select();
                showMessage('<img src="' + document.selection.createRange().text + '"/>');
            }
        }

还可以统计图片大小,IE8不支持
$.each(files,function(index,fileInfo){
         fileInfo.size;
});


深克隆对象

_deepClone: function (obj) {
            var newObj,that=this;
            if (typeof obj === 'string') {
                //字符串
                newObj = '' + obj;
            } else if ($.isArray(obj)) {
                //数组
                newObj = $.map(obj,function(elem,name){
                    return that._deepClone.call(that,elem);
                });
            } else if (typeof obj === 'object') {
                //对象
                newObj={};
                for (var name in obj) {
                    if (obj[name] instanceof Function) {
                        newObj[name] = obj[name].toString().replace(/[\n\r\t]/g, '').replace(/(\s)+/g, ' ').replace(/\+/g, '##plus##');
                    } else {
                        newObj[name] = this._deepClone(obj[name]);
                    }
                }
            }else{
                newObj=obj;
            }

            return newObj;
        },

此方法不仅将对象完完全全地复制一份,并且将函数也进行字符串化


技巧性方法

循环

作用:减少引用链,提高效率

方法1:
var i,max,
     list=[];
for(i=0,max=list.length;i<max;i++){
    //适用于对list[i]较少使用的情况,
}
方法2(jQuery源码使用的方法):
var i,elem,
     list=[];
for(i=0;(elem=list[i])!=null;i++){
    //适用于对list[i]引用较多的情况,或list[i]是一个对象
}
方法3(不用到索引index的情况下)
var i=0,
     elem=obj,
     list=Array;
     while((elem=list[i++])!=null){
     //elem是一个对象的时候
}


内部函数

作用:减少全局变量,module化编程,使得程序结构化,减少阅读程序难度
1.自定义简单型:

(function(){
    var i=nInt,
          list=Array,
          func=function(){};

         //使得函数、变量仅在该代码段内运行
         //减少代码冲突

});
2.请参考jQuery模式,研究中…稍后放出一个原创的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值