Home > Web Front-end > JS Tutorial > Summary of commonly used JavaScript scripts (1)_javascript skills

Summary of commonly used JavaScript scripts (1)_javascript skills

PHP中文网
Release: 2016-05-16 16:11:10
Original
1220 people have browsed it

This article mainly introduces the first article in the series of summary of common JavaScript scripts. What I will share with you is that jquery restricts the text box to only input numbers, encapsulates the DOMContentLoaded event, uses native JS to simply encapsulate AJAX, and cross-domain requests. JSONP, thousandth formatting, friends in need can refer to it.

jquery restricts the text box to only input numbers

jquery restricts the text box to only input numbers, compatible with IE, chrome, and FF (performance effects are different), sample code As follows:

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

The function of the above code is: only positive integers greater than 0 can be entered.

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

The function of the above code is: only numbers from 0-9 and decimal points can be entered.

Encapsulate DOMContentLoaded event

//Save the event queue of domReady
eventQueue = [];
//Judge whether the DOM is loaded
isReady = false;
//Judge whether the DOMReady is bound
isBind = false;
/*Execute domReady()
*
*@param {function}
*@execute Push the event handler into the event queue and bind DOMContentLoaded
* * If the DOM is loaded has been completed, execute immediately >                                                                                                     *@param null
*@execute Modern browsers bind DOMContentLoaded through addEvListener, including ie9
ie6-8 determines whether the DOM is loaded by judging doScroll
*@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 determines whether the DOM of ie6-8 is loaded Completed
*
*@param null
*@execute doScroll to determine whether the DOM is loaded
*@caller bindReady()
*/
function doScroll(){
try try {
                                                                                                                                                                                                                                                                                                   .​ 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 2
domReady(function(){
});
//Note, if it is asynchronously loaded js, do not bind the domReady method, otherwise the function It will not be executed,
//Because DOMContentLoaded has been triggered before the asynchronously loaded js is downloaded, addEventListener can no longer be monitored when it is executed



Use native JS to simply encapsulate AJAX


First, we need the xhr object. This is not difficult for us, encapsulate it into a function

var createAjax = function() {
var xhr = null;
try {
} Catch (e1) {
Try {
// Non -IE browser
xhr = new xmlhttprequest ();
} catch (e2) {
Window.alert ("Your browse The server does not support ajax, please change! ");
}
}
return xhr;
};


Then, let’s write the core function.

var ajax = function(conf) {
// Initialization
//type parameter, optional
var type = conf.type;
//url parameter, required
var url = conf.url;
//data parameter is optional, only required in post request
var data = conf.data;
//datatype parameter is optional
var dataType = conf. dataType;
//The callback function is optional
var success = conf.success;
if (type == null){
//The type parameter is optional, the default is get
type = "get";
}
if (dataType == null){
Create ajax engine object
var xhr = createAjax();
// Open
xhr.open(type, url, true);
// Send
if (type == "GET " || type == "get") {
                                                 ("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){
                                                                                                                                                        ==="XML") {
                                                                                                        != null){
                                                                                               (dataType=="json"||dataType=="JSON") {
               if (success != null){
                                                                                                                                                                                                                                                                              }
}
}
};
};
url:"test.jsp",
data:"name=dipoo&info=good",
dataType:"json",
success:function(data){
alert(data. name);
}
});



JSONP for cross-domain requests


/**
* Added handling of request failure. Although this function is not very useful, it studies the differences of scripts in various browsers
* 1, IE6/7/8 supports the onreadystatechange event of script
* 2. IE9/10 supports the onload and onreadystatechange events of script
* 3. Firefox/Safari/Chrome/Opera supports the onload event of script
* 4. IE6/7/8/Opera does not support the onerror event of script; IE9/10/Firefox/Safari/Chrome supports
* 5. Although Opera does not support the onreadystatechange event, it has the readyState attribute. This is amazing
* 6. Use IE9 and IETester to test IE6/7/8 , its readyState is always loading, loaded. Complete never appeared.
*
* The final implementation idea:
* 1. IE9/Firefox/Safari/Chrome uses the onload event for successful callbacks, and uses the onerror event for error callbacks
* 2. Opera also uses the onload event for successful callbacks (It does not support onreadystatechange at all). Since it does not support onerror, delayed processing is used here.
* That is, waiting for and success callback success, the flag bit done is set to true after success. Failure will not be executed, otherwise it will be executed.
* The value of the delay time here is very tricky. It was previously set to 2 seconds, and it was no problem when tested in the company. However, after using the 3G wireless network at home, I found that even though the referenced js file existed, due to
* the network speed was too slow, failure was executed first and success was executed later. So it is more reasonable to take 5 seconds here. Of course it's not absolute.
* 3, IE6/7/8 The success callback uses the onreadystatechange event, and the error callback is almost difficult to implement. It is also the most technical.
* Refer to //m.sbmmt.com/
* Use nextSibling and find that it cannot be implemented.
* What is disgusting is that even the requested resource file does not exist. Its readyState will also go through the "loaded" state. This way you can't tell whether the request succeeded or failed.
* I was afraid of it, so I finally used the front-end and back-end coordination mechanism to solve the last problem. Let it call callback(true) whether the request succeeds or fails.
* At this time, the logic to distinguish success and failure has been placed in the callback. If jsonp is not returned in the background, failure is called, otherwise success is called.
*
*
* Interface
* Sjax.load(url, {
* data ) // Request parameters (key-value pair string or js object)
* success // Request success callback function
* failure // Request failure callback function
* scope // Callback function execution context
* timestamp // Whether to add timestamp
* });
*
*/
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                    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){
🎜>              done = true;
                                                  //alert('warning: jsonp did not return.' );
}
}else{
failure.call(scope);
}
                              🎜>                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 == 'Loadeded' || ReadyState == { 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);

调用方式如下:

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

千分位格式化

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;

以上就是本文给大家分享的javascript常用脚本了,希望大家能够喜欢。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template