JavaScript共通スクリプトの要約(一)
13081 ワード
jquery制限テキストボックスには数値しか入力できません
jquery制限テキストボックスには数字しか入力できません.IE、chrome、FFと互換性があります.サンプルコードは以下の通りです.
上のコードの役割は、0より大きい正の整数しか入力できません.
上のコードの役割は、0-9の数字と小数点しか入力できません.
DOMContentLoadedイベントのカプセル化
原生JSでAJAXをシンプルにパッケージング
まず、xhrオブジェクトが必要です.これは私たちにとって難しくなく、関数にカプセル化されています.
次に、コア関数を書きます.
最後に、この関数の使い方を説明します.
ドメイン間要求のJSONP
呼び出し方法は次のとおりです.
マイクロビットフォーマット
以上、本文で共有したjavascriptの常用スクリプトですが、気に入ってほしいです.
jquery制限テキストボックスには数字しか入力できません.IE、chrome、FFと互換性があります.サンプルコードは以下の通りです.
$("input").keyup(function(){ //keyup
$(this).val($(this).val().replace(/\D|^0/g,''));
}).bind("paste",function(){ //CTR+V
$(this).val($(this).val().replace(/\D|^0/g,''));
}).css("ime-mode", "disabled"); //CSS
上のコードの役割は、0より大きい正の整数しか入力できません.
$("#rnumber").keyup(function(){
$(this).val($(this).val().replace(/[^0-9.]/g,''));
}).bind("paste",function(){ //CTR+V
$(this).val($(this).val().replace(/[^0-9.]/g,''));
}).css("ime-mode", "disabled"); //CSS
上のコードの役割は、0-9の数字と小数点しか入力できません.
DOMContentLoadedイベントのカプセル化
// domReady
eventQueue = [];
// DOM
isReady = false;
// DOMReady
isBind = false;
/* domReady()
*
*@param {function}
*@execute , DOMContentLoaded
* DOM ,
*@caller
*/
function domReady(fn){
if (isReady) {
fn.call(window);
}
else{
eventQueue.push(fn);
};
bindReady();
};
/*domReady
*
*@param null
*@execute addEvListener DOMContentLoaded, ie9+
ie6-8 doScroll DOM
*@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 ie6-8 DOM
*
*@param null
*@execute doScroll DOM
*@caller bindReady()
*/
function doScroll(){
try{
document.documentElement.doScroll('left');
}
catch(error){
return setTimeout(doScroll,20);
};
execFn();
};
/*
*
*@param null
*@execute
*@caller bindReady()
*/
function execFn(){
if (!isReady) {
isReady = true;
for (var i = 0; i < eventQueue.length; i++) {
eventQueue[i].call(window);
};
eventQueue = [];
};
};
//js 1
domReady(function(){
});
//js 2
domReady(function(){
});
// , js domReady , ,
// js ,DOMContentLoaded ,addEventListener
原生JSでAJAXをシンプルにパッケージング
まず、xhrオブジェクトが必要です.これは私たちにとって難しくなく、関数にカプセル化されています.
var createAjax = function() {
var xhr = null;
try {
//IE
xhr = new ActiveXObject("microsoft.xmlhttp");
} catch (e1) {
try {
// IE
xhr = new XMLHttpRequest();
} catch (e2) {
window.alert(" ajax, !");
}
}
return xhr;
};
次に、コア関数を書きます.
var ajax = function(conf) {
//
//type ,
var type = conf.type;
//url ,
var url = conf.url;
//data , post
var data = conf.data;
//datatype
var dataType = conf.dataType;
//
var success = conf.success;
if (type == null){
//type , get
type = "get";
}
if (dataType == null){
//dataType , text
dataType = "text";
}
// ajax
var xhr = createAjax();
//
xhr.open(type, url, true);
//
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){
//
success(xhr.responseText);
}
}else if(dataType=="xml"||dataType=="XML") {
if (success != null){
// xml
success(xhr.responseXML);
}
}else if(dataType=="json"||dataType=="JSON") {
if (success != null){
// json js
success(eval("("+xhr.responseText+")"));
}
}
}
};
};
最後に、この関数の使い方を説明します.
ajax({
type:"post",
url:"test.jsp",
data:"name=dipoo&info=good",
dataType:"json",
success:function(data){
alert(data.name);
}
});
ドメイン間要求のJSONP
/**
* JavaScript JSONP Library v0.3
* Copyright (c) 2011 snandy
* QQ : 34580561
* Date: 2011-04-26
*
* , , script
* 1, IE6/7/8 script onreadystatechange
* 2, IE9/10 script onload onreadystatechange
* 3, Firefox/Safari/Chrome/Opera script onload
* 4, IE6/7/8/Opera script onerror ; IE9/10/Firefox/Safari/Chrome
* 5, Opera onreadystatechange , readyState .
* 6, IE9 IETester IE6/7/8, readyState loading,loaded。 complete。
*
* :
* 1, IE9/Firefox/Safari/Chrome onload , onerror
* 2, Opera onload ( onreadystatechange), onerror, 。
* success,success done true。failure , 。
* , 2 , 。 3G js ,
* ,failure , success。 5 。 。
* 3, IE6/7/8 onreadystatechange , 。 。
* http://stackoverflow.com/questions/3483919/script-onload-onerror-with-iefor-lazy-loading-problems
* nextSibling, 。
* , 。 readyState “loaded” 。 。
* , 。 callback(true)。
* callback , jsonp failure, success。
*
*
*
* Sjax.load(url, {
* data // ( js )
* success //
* failure //
* scope //
* 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){
if(typeof jsonp != 'undefined'){// jsonp ,
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);
呼び出し方法は次のとおりです.
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の常用スクリプトですが、気に入ってほしいです.