Summary of JavaScript common scripts (I)

  • 2020-05-10 17:43:54
  • OfStack

jquery restricts text boxes to Numbers only

jquery limits the text box to enter only Numbers, and it is compatible with IE, chrome and FF (the performance effect is not the same). The sample code is as follows:


$("input").keyup(function(){ //keyup The event processing
   $(this).val($(this).val().replace(/\D|^0/g,''));
}).bind("paste",function(){ //CTR+V The event processing
   $(this).val($(this).val().replace(/\D|^0/g,''));
}).css("ime-mode", "disabled"); //CSS Setup input method not available

The above code is used to enter only positive integers greater than 0.


$("#rnumber").keyup(function(){ 
        $(this).val($(this).val().replace(/[^0-9.]/g,'')); 
    }).bind("paste",function(){  //CTR+V The event processing  
        $(this).val($(this).val().replace(/[^0-9.]/g,''));  
    }).css("ime-mode", "disabled"); //CSS Setup input method not available

The above code only allows you to enter Numbers and decimal points from 0 to 9.

Encapsulate the DOMContentLoaded event


// save domReady Event queue of
    eventQueue = [];
    // judge DOM Whether the loading is finished
    isReady = false;
    // judge DOMReady Whether the binding
    isBind = false;
    /* perform domReady()
     *
     *@param    {function}
     *@execute  Presses the event handler into the event queue , And bind the DOMContentLoaded
     *          if DOM The load is complete and is executed immediately
     *@caller
     */
    function domReady(fn){
        if (isReady) {
            fn.call(window);
        }
        else{
            eventQueue.push(fn);
        };
        bindReady();
    };
    /*domReady event
     *
     *@param    null
     *@execute  Modern browsers pass addEvListener The binding DOMContentLoaded, including ie9+
     ie6-8 By judging doScroll judge DOM Whether the loading is finished
     *@caller   domReady()
     */
    function bindReady(){
        if (isReady) return;
        if (isBind) return;
        isBind = true;
        if (window.addEventListener) {
            document.addEventListener('DOMContentLoaded',execFn,false);
        }
        else if (window.attachEvent) {
            doScroll();
        };
    };
    /*doScroll judge ie6-8 the DOM Whether the loading is completed or not
     *
     *@param    null
     *@execute  doScroll judge DOM Whether the loading is completed or not
     *@caller   bindReady()
     */
    function doScroll(){
        try{
            document.documentElement.doScroll('left');
        }
        catch(error){
            return setTimeout(doScroll,20);
        };
        execFn();
    };
    /* Execute event queue
     *
     *@param    null
     *@execute  Loop the event handler in the execution queue
     *@caller   bindReady()
     */
    function execFn(){
        if (!isReady) {
            isReady = true;
            for (var i = 0; i < eventQueue.length; i++) {
                eventQueue[i].call(window);
            };
            eventQueue = [];
        };
    };
    //js file 1
    domReady(function(){
    });
    //js file 2
    domReady(function(){
    });
    // Note that if it is loaded asynchronously js Don't bind domReady Method, otherwise the function won't execute,
    // Because it's loaded asynchronously js Before downloading, DOMContentLoaded Has been triggered, addEventListener Execution time has been unable to listen

Simple encapsulation of AJAX with native JS

First, we need the xhr object. It's not hard for us to encapsulate it as a function.


var createAjax = function() {
    var xhr = null;
    try {
        //IE Serial browser
        xhr = new ActiveXObject("microsoft.xmlhttp");
    } catch (e1) {
        try {
            // non IE The browser
            xhr = new XMLHttpRequest();
        } catch (e2) {
            window.alert(" Your browser does not support it ajax Please change it! ");
        }
    }
    return xhr;
};   

And then, let's write the core function.


var ajax = function(conf) {
    // Initialize the
    //type parameter , optional
    var type = conf.type;
    //url Parameter, required
    var url = conf.url;
    //data Parameters are optional, only in post Upon request
    var data = conf.data;
    //datatype Parameters can be chosen    
    var dataType = conf.dataType;
    // The callback function is optional
    var success = conf.success;
    if (type == null){
        //type Parameter is optional and defaults to get
        type = "get";
    }
    if (dataType == null){
        //dataType Parameter is optional and defaults to text
        dataType = "text";
    }
    // create ajax Engine object
    var xhr = createAjax();
    // Open the
    xhr.open(type, url, true);
    // send
    if (type == "GET" || type == "get") {
        xhr.send(null);
    } else if (type == "POST" || type == "post") {
        xhr.setRequestHeader("content-type",
                    "application/x-www-form-urlencoded");
        xhr.send(data);
    }
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            if(dataType == "text"||dataType=="TEXT") {
                if (success != null){
                    // Plain text
                    success(xhr.responseText);
                }
            }else if(dataType=="xml"||dataType=="XML") {
                if (success != null){
                    // receive xml The document    
                    success(xhr.responseXML);
                } 
            }else if(dataType=="json"||dataType=="JSON") {
                if (success != null){
                    // will json String conversion to js object  
                    success(eval("("+xhr.responseText+")"));
                }
            }
        }
    };
};      

Finally, explain the use of this function for 1.


    ajax({
        type:"post",
        url:"test.jsp",
        data:"name=dipoo&info=good",
        dataType:"json",
        success:function(data){
            alert(data.name);
        }
    }); 

JSONP for cross-domain requests


/**
 * JavaScript JSONP Library v0.3
 * Copyright (c) 2011 snandy
 * QQ Group of : 34580561
 * Date: 2011-04-26
 *
 * Add the handling of failed requests, although this feature is not very useful, but has been studied under various browsers script The differences of
 * 1, IE6/7/8 support script the onreadystatechange The event
 * 2, IE9/10 support script the onload and onreadystatechange The event
 * 3, Firefox/Safari/Chrome/Opera support script the onload The event
 * 4, IE6/7/8/Opera Does not support script the onerror The event ; IE9/10/Firefox/Safari/Chrome support
 * 5, Opera Although not supported onreadystatechange The event , But it has readyState attribute . This is amazing
 * 6, with IE9 and IETester test IE6/7/8 , its readyState The total for loading,loaded . Have not seen complete .
 *
 * The final realization idea:
 * 1, IE9/Firefox/Safari/Chrome Successful callback use onload Event, error callback is used onerror The event
 * 2, Opera Successful callbacks are also used onload Event (it does not support at all onreadystatechange ) because it is not supported onerror , where deferred processing is used.
 *    Wait and successful callback success . success After the sign bit done Set to true . failure It will not be executed, otherwise it will be executed.
 *    It's a little tricky to evaluate the time delay here 2 Second, no problem in the company test. But the home use 3G Wireless network found even after the reference js The file exists, but because
 *    The Internet speed is too slow, failure I'm going to do it first, and then I'm going to do it success . So let's take 5 Seconds is reasonable. Not absolutely, of course.
 * 3, IE6/7/8 Successful callback use onreadystatechange Event, error callbacks are almost impossible to implement. It's also the most technical.
 *    Refer to the http://stackoverflow.com/questions/3483919/script-onload-onerror-with-iefor-lazy-loading-problems
 *    use nextSibling , discovery cannot be achieved.
 *    The disgusting thing is, even if the requested resource file doesn't exist. It's readyState Will also experience" loaded "State. You won't be able to tell the difference between successful and unsuccessful requests.
 *    Afraid of it, use front and back end finally 1 A coordinated mechanism to solve the final problem. Let the request be called whether it succeeds or fails callback(true) .
 *    The logic that distinguishes success from failure has been put in place callback If the background does not return jsonp The call failure , otherwise call success .
 *   
 *
 * interface
 * Sjax.load(url, {
 *    data      // Request parameters ( Key value against string or js object )
 *    success   // Request successful callback function
 *    failure   // Request failed callback function
 *    scope     // Callback function execution context
 *    timestamp // Time stamped or not
 * });
 *
 */
Sjax =
function(win){
    var ie678 = !-[1,],
        opera = win.opera,
        doc = win.document,
        head = doc.getElementsByTagName('head')[0],
        timeout = 3000,
        done = false;
    function _serialize(obj){
        var a = [], key, val;
        for(key in obj){
            val = obj[key];
            if(val.constructor == Array){
                for(var i=0,len=val.length;i<len;i++){
                    a.push(key + '=' + encodeURIComponent(val[i]));
                }
            }else{
                a.push(key + '=' + encodeURIComponent(val));
            }
        }
        return a.join('&');
    }
    function request(url,opt){
        function fn(){}
        var opt = opt || {},
        data = opt.data,
        success = opt.success || fn,
        failure = opt.failure || fn,
        scope = opt.scope || win,
        timestamp = opt.timestamp;
        if(data && typeof data == 'object'){
            data = _serialize(data);
        }      
        var script = doc.createElement('script');
        function callback(isSucc){
            if(isSucc){
                if(typeof jsonp != 'undefined'){// Assign to the right jsonp Must be returned from the background. This variable is a global variable
                    done = true;
                    success.call(scope, jsonp);
                }else{
                    failure.call(scope);
                    //alert('warning: jsonp did not return.');
                }
            }else{
                failure.call(scope);
            }
            // Handle memory leak in IE
            script.onload = script.onerror = script.onreadystatechange = null;
            jsonp = undefined;
            if( head && script.parentNode ){
                head.removeChild(script);
            }
        }
        function fixOnerror(){
            setTimeout(function(){
                if(!done){
                    callback();
                }
            }, timeout);
        }
        if(ie678){
            script.onreadystatechange = function(){
                var readyState = this.readyState;
                if(!done && (readyState == 'loaded' || readyState == 'complete')){
                    callback(true);
                }
            }
            //fixOnerror();
        }else{
            script.onload = function(){
                callback(true);
            }
            script.onerror = function(){
                callback();
            }
            if(opera){
                fixOnerror();
            }
        }
        if(data){
            url += '?' + data;
        }
        if(timestamp){
            if(data){
                url += '&ts=';
            }else{
                url += '?ts='
            }
            url += (new Date).getTime();
        }
        script.src = url;
        head.insertBefore(script, head.firstChild);
    }
    return {load:request};
}(this);

The method of invocation is as follows:


 Sjax.load('jsonp66.js', {
        success : function(){alert(jsonp.name)},
        failure : function(){alert('error');}
  }); 

Thousandth bit formatting


function toThousands(num) {
    var num = (num || 0).toString(), result = '';
    while (num.length > 3) {
        result = ',' + num.slice(-3) + result;
        num = num.slice(0, num.length - 3);
    }
    if (num) { result = num + result; }
    return result;

These are the common javascript scripts that I share with you in this article. I hope you like them.


Related articles: