jquery restricts text box to enter only numbers
jquery restricts the text box to enter only numbers, which are compatible with IE, chrome, and FF (the performance effect is different). The sample code is as follows:
The code copy is 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 purpose of the above code is: Only positive integers greater than 0 can be entered.
The code copy is as follows:
$("#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 purpose of the above code is: only 0-9 numbers and decimal points can be entered.
Encapsulate DOMContentLoaded event
The code copy is as follows:
//Save the event queue of domReady
eventQueue = [];
//Judge whether the DOM has been loaded
isReady = false;
//Judge whether DOMReady is bound
isBind = false;
/*Execute domReady()
*
*@param {function}
*@execute pushes the event handler into the event queue and binds DOMContentLoaded
* If the DOM loading has been completed, execute immediately
*@caller
*/
function domReady(fn){
if (isReady) {
fn.call(window);
}
else{
eventQueue.push(fn);
};
bindReady();
};
/*domReady event binding
*
*@param null
*@execute Modern browsers bind DOMContentLoaded through addEvListener, including ie9+
ie6-8 determines whether the DOM has been 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 has been loaded.
*
*@param null
*@execute doScroll determines whether the DOM is loading
*@caller bindReady()
*/
function doScroll(){
try{
document.documentElement.doScroll('left');
}
catch(error){
return setTimeout(doScroll,20);
};
execFn();
};
/*Execution event queue
*
*@param null
*@execute loop execution event handler in 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, do not bind the domReady method, otherwise the function will not be executed.
//Because before the asynchronous loading js download, DOMContentLoaded has been fired, and the addEventListener cannot be listened to when executing
Simple encapsulation of AJAX using native JS
First, we need the xhr object. This is not difficult for us, encapsulating it into a function.
The code copy is as follows:
var createAjax = function() {
var xhr = null;
try {
//IE series browser
xhr = new ActiveXObject("microsoft.xmlhttp");
} catch (e1) {
try {
//Not IE browser
xhr = new XMLHttpRequest();
} catch (e2) {
window.alert("Your browser does not support ajax, please replace it!");
}
}
return xhr;
};
Then, let's write the core function.
The code copy is as follows:
var ajax = function(conf) {
// Initialization
//type parameter, optional
var type = conf.type;
//url parameters, required
var url = conf.url;
//Data parameter is optional, only required when requesting post
var data = conf.data;
//Datatype parameter is optional
var dataType = conf.dataType;
//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){
//The dataType parameter is optional, default to text
dataType = "text";
}
// Create ajax engine object
var xhr = createAjax();
// Open
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){
//Normal text
success(xhr.responseText);
}
}else if(dataType=="xml"||dataType=="XML") {
if (success != null){
//Receive xml documents
success(xhr.responseXML);
}
}else if(dataType=="json"||dataType=="JSON") {
if (success != null){
//Convert json string to js object
success(eval("("+xhr.responseText+")"));
}
}
}
};
};
Finally, let’s explain the usage of this function.
The code copy is as follows:
ajax({
type:"post",
url:"test.jsp",
data:"name=dipoo&info=good",
dataType:"json",
success:function(data){
alert(data.name);
}
});
Cross-domain requests JSONP
The code copy is as follows:
/**
* JavaScript JSONP Library v0.3
* Copyright (c) 2011 snandy
* QQ group: 34580561
* Date: 2011-04-26
*
* Increase the handling of request failures. Although this function is not very useful, the differences in scripts in each browser were studied.
* 1, IE6/7/8 onreadystatechange event that supports script
* 2, IE9/10 supports script onload and onreadystatechange events
* 3, Firefox/Safari/Chrome/Opera supports script onload events
* 4, IE6/7/8/Opera does not support script onerror event; IE9/10/Firefox/Safari/Chrome supports
* 5. Although Opera does not support the onreadystatechange event, it has the readyState property. This is very magical
* 6. Test IE6/7/8 with IE9 and IETester, and its readyState is always loading and loaded. No complete has appeared.
*
* The final implementation idea:
* 1, IE9/Firefox/Safari/Chrome successfully called back to use onload event, and the error callback uses onerror event
* 2, Opera successfully callback also uses the onload event (it does not support onreadystatechange at all). Since it does not support onerror, delay processing is used here.
* That is, wait for success and successfully callback, and the flag bit done after success is set to true. Failure will not be executed, otherwise it will be executed.
* It is very skillful to take the delayed time value here. It takes 2 seconds before, and there is no problem in the company testing. But after going home to use the 3G wireless network, I found that even though the referenced js file exists, it is
* The internet speed is too slow, failure is executed first and then success. So it is more reasonable to take 5 seconds here. Of course, it is not absolute.
* 3, IE6/7/8 Successful callbacks use the onreadystatechange event, and error callbacks are almost difficult to implement. It is also the most technical.
* Reference http://stackoverflow.com/questions/3483919/script-onload-onerror-with-iefor-lazy-loading-problems
* Using nextSibling, it was found that it could not be implemented.
* What's disgusting is that even if the requested resource file does not exist. Its readyState will also experience a "loaded" state. This way you can't tell whether the request succeeds or fails.
* I am afraid of it, so I finally use the mechanism of coordination between the front and back office to solve the final problem. Make the request callback(true) regardless of success or failure.
* At this time, the logic that distinguishes success and failure has been put into the callback. If the background does not return jsonp, call failure, otherwise call success.
*
*
* Interface
* Sjax.load(url, {
* data // Request parameters (key value pair string or js object)
* success // Request successful callback function
* failure // The callback function failed
* scope // Callback function execution context
* timestamp // Whether to add a time stamp
* });
*
*/
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'){// The jsonp on the right of the assignment must be returned in the background, and 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 call method is as follows:
The code copy is as follows:
Sjax.load('jsonp66.js', {
success : function(){alert(jsonp.name)},
failure : function(){alert('error');}
});
Millometer formatting
The code copy is as follows:
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;
}
The above are the commonly used javascript scripts shared by this article. I hope you like them.