Summary of commonly used JavaScript scripts (1)_javascript skills
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 http://www.php.cn/
* 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
}
}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 == {
}
}
//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常用脚本了,希望大家能够喜欢。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
