jquery属性に関するjs実装方法
104895 ワード
第三者のjqueryやzeptioを使わず、オリジナルのjavascriptを直接使う会社もある。オリジナルjavascript機能は強力ですが、一部のプロパティではIE 8以下のブラウザはサポートされていません。次にjqueryに関する方法をjsでどのように実現するかを簡単にまとめます。
要素アクション
Add Class
//JQUERY $(el).addClass(className);//js// , ,IE8+if(el.classList) el.classList.add(className);else el.className +=' '+ className;// , ,IE10+ el.classList.add(className);
After
//JQUERY $(el).after(htmlString);//js , ,IE8+ el.insertAdjacentHTML('afterend', htmlString);
Append
//JQUERY $(parent).append(el);//js , ,IE8+ parent.appendChild(el);
Before
//JQUERY $(el).before(htmlString);//js , ,IE8+ el.insertAdjacentHTML('beforebegin', htmlString);
Children
//JQUERY $(el).children();//js// , ,IE8+var children =[];for(var i = el.children.length; i--;){// Skip comment nodes on IE8if(el.children[i].nodeType !=8) children.unshift(el.children[i]);}// , ,IE9+ el.children
Clone
//JQUERY $(el).clone();// , ,IE8+ el.cloneNode(true);
Contains
//JQUERY $.contains(el, child);// , ,IE8+ el !== child && el.contains(child);
Contains Selector
//JQUERY $(el).find(selector).length;// , ,IE8+ el.querySelector(selector)!==null
Each
//JQUERY $(selector).each(function(i, el){});//js , ,IE8+function forEachElement(selector, fn){var elements = document.querySelectorAll(selector);for(var i =0; i < elements.length; i++) fn(elements[i], i);} forEachElement(selector,function(el, i){});//js , ,IE9+var elements = document.querySelectorAll(selector);Array.prototype.forEach.call(elements,function(el, i){});
Empty
//JQUERY $(el).empty();//js , ,IE8+while(el.firstChild) el.removeChild(el.firstChild);//js , ,IE9+ el.innerHTML ='';
ろ過フィルター
//JQUERY $(selector).filter(filterFn);// , ,IE8+function filter(selector, filterFn){var elements = document.querySelectorAll(selector);varout=[];for(var i = elements.length; i--;){if(filterFn(elements[i]))out.unshift(elements[i]);}returnout;} filter(selector, filterFn);// , ,IE9+Array.prototype.filter.call(document.querySelectorAll(selector), filterFn);
サブエレメントの検索
//JQUERY $(el).find(selector);// , ,IE8+ el.querySelectorAll(selector);
検索、セレクタ
//JQUERY $('.my #awesome selector');// , ,IE8+ document.querySelectorAll('.my #awesome selector');
属性値attrの取得
//JQUERY $(el).attr('tabindex');// , ,IE8+ el.getAttribute('tabindex');
Htmlコンテンツの取得
//JQUERY $(el).html();//js el.innerHTML
CSSスタイルの取得
//JQUERY $(el).css(ruleName);// , ,IE9+ getComputedStyle(el)[ruleName];
テキストの内容の取得
//JQUERY $(el).text();// , ,IE8+ el.textContent || el.innerText // , ,IE9+ el.textContent
Has Class
//JQUERY $(el).hasClass(className);// , ,IE8+if(el.classList) el.classList.contains(className);elsenewRegExp('(^| )'+ className +'( |$)','gi').test(el.className);// , ,IE10+ el.classList.contains(className);
要素の比較
JQUERY $(el).is($(otherEl));//js el === otherEl
クラス名の比較
//JQUERY $(el).is('.my-class');// , ,IE8+var matches =function(el, selector){var _matches =(el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector);if(_matches){return _matches.call(el, selector);}else{var nodes = el.parentNode.querySelectorAll(selector);for(var i = nodes.length; i--;){if(nodes[i]=== el)returntrue;}returnfalse;}}; matches(el,'.my-class');// , ,IE9+var matches =function(el, selector){return(el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);}; matches(el,'.my-class');
Next
//JQUERY $(el).next();// , ,IE8+// nextSibling can include text nodesfunction nextElementSibling(el){do{ el = el.nextSibling;}while( el && el.nodeType !==1);return el;} el.nextElementSibling || nextElementSibling(el);// , ,IE9+ el.nextElementSibling
Offset
//JQUERY $(el).offset();//js , ,IE8+var rect = el.getBoundingClientRect(){ top: rect.top + document.body.scrollTop, left: rect.left + document.body.scrollLeft }
Outer Width
//JQUERY $(el).outerWidth();//js el.offsetWidth
Parent
//JQUERY $(el).parent();//js el.parentNode
Position
//JQUERY $(el).position();//js{left: el.offsetLeft, top: el.offsetTop}
Prev
//JQUERY $(el).prev();// , ,IE8+// prevSibling can include text nodesfunction previousElementSibling(el){do{ el = el.previousSibling;}while( el && el.nodeType !==1);return el;} el.previousElementSibling || previousElementSibling(el);// , ,IE9+ el.previousElementSibling
Remove
//JQUERY $(el).remove();//js , ,IE8+ el.parentNode.removeChild(el);
Remove Class
//JQUERY $(el).removeClass(className);//js , ,IE8+if(el.classList) el.classList.remove(className);else el.className = el.className.replace(newRegExp('(^|\\b)'+ className.split(' ').join('|')+'(\\b|$)','gi'),' ');// , ,IE10+ el.classList.remove(className);
Replace From Html
//JQUERY $(el).replaceWith(string);// , ,IE8+ el.outerHTML =string;
Set Attributes
//JQUERY $(el).attr('tabindex',3);// , ,IE8+ el.setAttribute('tabindex',3);
Set Html
//JQUERY $(el).html(string);// , ,IE8+ el.innerHTML =string;
Set Style
//JQUERY $(el).css('border-width','20px');// , ,IE8+// Use a class if possible el.style.borderWidth ='20px';
Set Text
//JQUERY $(el).text(string);// , ,IE8+if(el.textContent !==undefined) el.textContent =string;else el.innerText =string;// , ,IE9+ el.textContent =string;
Siblings
//JQUERY $(el).siblings();// , ,IE8+var siblings =Array.prototype.slice.call(el.parentNode.children);for(var i = siblings.length; i--;){if(siblings[i]=== el){ siblings.splice(i,1);break;}}// , ,IE9+Array.prototype.filter.call(el.parentNode.children,function(child){return child !== el;});
Toggle Class
//JQUERY $(el).toggleClass(className);// , ,IE8+if(el.classList){ el.classList.toggle(className);}else{var classes = el.className.split(' ');var existingIndex =-1;for(var i = classes.length; i--;){if(classes[i]=== className) existingIndex = i;}if(existingIndex >=0) classes.splice(existingIndex,1);else classes.push(className); el.className = classes.join(' ');}// , ,IE9+if(el.classList){ el.classList.toggle(className);}else{var classes = el.className.split(' ');var existingIndex = classes.indexOf(className);if(existingIndex >=0) classes.splice(existingIndex,1);else classes.push(className); el.className = classes.join(' ');}// , ,IE10+ el.classList.toggle(className);
≪イベント|Events|ldap≫
Off
//JQUERY $(el).off(eventName, eventHandler);// , ,IE8+function removeEventListener(el, eventName, handler){if(el.removeEventListener) el.removeEventListener(eventName, handler);else el.detachEvent('on'+ eventName, handler);} removeEventListener(el, eventName, handler);// , ,IE9+ el.removeEventListener(eventName, eventHandler);
On
//JQUERY $(el).on(eventName, eventHandler);// , ,IE8+function addEventListener(el, eventName, handler){if(el.addEventListener){ el.addEventListener(eventName, handler);}else{ el.attachEvent('on'+ eventName,function(){ handler.call(el);});}} addEventListener(el, eventName, handler); , ,IE9+ el.addEventListener(eventName, eventHandler);
Ready
//JQUERY $(document).ready(function(){});// , ,IE8+function ready(fn){if(document.readyState !='loading'){ fn();}elseif(document.addEventListener){ document.addEventListener('DOMContentLoaded', fn);}else{ document.attachEvent('onreadystatechange',function(){if(document.readyState !='loading') fn();});}}// , ,IE9+function ready(fn){if(document.readyState !='loading'){ fn();}else{ document.addEventListener('DOMContentLoaded', fn);}
イベントトリガの指定
//JQUERY $(el).trigger('my-event',{some:'data'});//js , ,IE9+if(window.CustomEvent){varevent=newCustomEvent('my-event',{detail:{some:'data'}});}else{varevent= document.createEvent('CustomEvent');event.initCustomEvent('my-event',true,true,{some:'data'});} el.dispatchEvent(event);
Trigger Native
//JQUERY $(el).trigger('change');// , ,IE8+if(document.createEvent){varevent= document.createEvent('HTMLEvents');event.initEvent('change',true,false); el.dispatchEvent(event);}else{ el.fireEvent('onchange');}// , ,IE9+// For a full list of event types: https://developer.mozilla.org/en-US/docs/Web/API/document.createEventvarevent= document.createEvent('HTMLEvents');event.initEvent('change',true,false); el.dispatchEvent(event);
テクニック
Array Each
//JQUERY $.each(array,function(i, item){}); , ,IE8+function forEach(array, fn){for(i =0; i < array.length; i++) fn(array[i], i);} forEach(array,function(item, i){});// , ,IE9+ array.forEach(function(item, i){});
デプス拡張
//JQUERY $.extend(true,{}, objA, objB);// , ,IE8+var deepExtend =function(out){out=out||{};for(var i =1; i < arguments.length; i++){var obj = arguments[i];if(!obj)continue;for(var key in obj){if(obj.hasOwnProperty(key)){if(typeof obj[key]==='object') deepExtend(out[key], obj[key]);elseout[key]= obj[key];}}}returnout;}; deepExtend({}, objA, objB);
proxy
//JQUERY $.proxy(fn, context);// , ,IE8+ fn.apply(context, arguments);// , ,IE9+ fn.bind(context);
bind
//jQuery $.extend({}, objA, objB);// , ,IE8+var extend =function(out){out=out||{};for(var i =1; i < arguments.length; i++){if(!arguments[i])continue;for(var key in arguments[i]){if(arguments[i].hasOwnProperty(key))out[key]= arguments[i][key];}}returnout;}; extend({}, objA, objB);
Index Of
//JQUERY $.inArray(item, array);// , ,IE8+function indexOf(array, item){for(var i =0; i < array.length; i++){if(array[i]=== item)return i;}return-1;} indexOf(array, item); , ,IE9+ array.indexOf(item);
Is Array
//JQUERY $.isArray(arr);// , ,IE8+ isArray =Array.isArray ||function(arr){returnObject.prototype.toString.call(arr)=='[object Array]';} isArray(arr);// , ,IE9+Array.isArray(arr);
Map
//JQUERY $.map(array,function(value, index){});//js , ,IE8+function map(arr, fn){var results =[];for(var i =0; i < arr.length; i++) results.push(fn(arr[i], i));return results;} map(array,function(value, index){});// , ,IE9+ array.map(function(value, index){});
Now
//JQUERY $.now();// , ,IE8+newDate().getTime();// , ,IE9+Date.now();
Parse Html
//JQUERY $.parseHTML(htmlString); , ,IE8+var parseHTML =function(str){var el = document.createElement('div'); el.innerHTML = str;return el.children;}; parseHTML(htmlString); , ,IE9+var parseHTML =function(str){var tmp = document.implementation.createHTMLDocument(); tmp.body.innerHTML = str;return tmp.body.children;}; parseHTML(htmlString);
解析Json
//JQUERY $.parseJSON(string);// , ,IE8+ JSON.parse(string);
Trim
//JQUERY $.trim(string);// , ,IE8+string.replace(/^\s+|\s+$/g,'');// , ,IE9+string.trim();
Type
//JQUERY $.type(obj); , ,IE8+Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/,"$1").toLowerCase();
ajax
新しいAJAXメソッドfetch()
基本Fetchの使い方
まず、XMLHttpRequestの使用とfetchの使用の違いを一例で比較してみましょう.私たちはURLを要求して、JSON形式の戻り結果を取得します.
元のXMLHttpRequest
XMLHttpRequestリクエストでは、successとerrorの2つのシナリオをキャプチャするために2つのリスナーが必要であり、open()メソッドとsend()メソッドを呼び出す必要があります.function reqListener(){var data = JSON.parse(this.responseText); console.log(data);}function reqError(err){ console.log('Fetch Error :-S', err);}var oReq =newXMLHttpRequest(); oReq.onload = reqListener; oReq.onerror = reqError; oReq.open('get','./api/some.json',true); oReq.send();
Fetchメソッド:
私たちのfetchリクエストのコードは基本的にこうです.fetch('./api/some.json').then(function(response){if(response.status !==200){ console.log('Looks like there was a problem. Status Code: '+ response.status);return;}// Examine the text in the response response.json().then(function(data){ console.log(data);});}).catch(function(err){ console.log('Fetch Error :-S', err);});
fetchによるフォームデータコミットの実行
WEBアプリケーションでは、フォームのコミットは非常に一般的な操作であり、fetchでフォームデータをコミットするのも非常に簡潔である.
fetchにはmethodとbodyパラメータのオプションが用意されています.fetch(url,{ method:'post', headers:{"Content-type":"application/x-www-form-urlencoded; charset=UTF-8"}, body:'foo=bar&lorem=ipsum'}).then(json).then(function(data){ console.log('Request succeeded with JSON response', data);}).catch(function(error){ console.log('Request failed', error);});
Fetchリクエストにユーザ認証情報を送信
fetchリクエストにcookiesなどの証明書情報を添付したい場合は、credentialsパラメータを「include」値に設定できます.fetch(url,{ credentials:'include'})
JSON
//JQUERY $.getJSON('/my/url',function(data){});// , ,IE8+var request =newXMLHttpRequest(); request.open('GET','/my/url',true); request.onreadystatechange =function(){if(this.readyState ===4){if(this.status >=200&&this.status <400){// Success!var data = JSON.parse(this.responseText);}else{// Error :(}}}; request.send(); request =null;// , ,IE9+var request =newXMLHttpRequest(); request.open('GET','/my/url',true); request.onload =function(){if(request.status >=200&& request.status <400){// Success!var data = JSON.parse(request.responseText);}else{// We reached our target server, but it returned an error}}; request.onerror =function(){// There was a connection error of some sort}; request.send();// , ,IE10+var request =newXMLHttpRequest(); request.open('GET','/my/url',true); request.onload =function(){if(this.status >=200&&this.status <400){// Success!var data = JSON.parse(this.response);}else{// We reached our target server, but it returned an error}}; request.onerror =function(){// There was a connection error of some sort}; request.send();
Post
//JQUERY $.ajax({ type:'POST', url:'/my/url', data: data });// , ,IE8+var request =newXMLHttpRequest(); request.open('POST','/my/url',true); request.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8'); request.send(data);
Request
//JQUERY $.ajax({ type:'GET', url:'/my/url', success:function(resp){}, error:function(){}});// , ,IE8+var request =newXMLHttpRequest(); request.open('GET','/my/url',true); request.onreadystatechange =function(){if(this.readyState ===4){if(this.status >=200&&this.status <400){// Success!var resp =this.responseText;}else{// Error :(}}}; request.send(); request =null;// , ,IE9+var request =newXMLHttpRequest(); request.open('GET','/my/url',true); request.onload =function(){if(request.status >=200&& request.status <400){// Success!var resp = request.responseText;}else{// We reached our target server, but it returned an error}}; request.onerror =function(){// There was a connection error of some sort}; request.send();// , ,IE10+var request =newXMLHttpRequest(); request.open('GET','/my/url',true); request.onload =function(){if(this.status >=200&&this.status <400){// Success!var resp =this.response;}else{// We reached our target server, but it returned an error}}; request.onerror =function(){// There was a connection error of some sort}; request.send();
特効
フェードアウト
//JQUERY $(el).fadeIn();// , ,IE8+function fadeIn(el){var opacity =0; el.style.opacity =0; el.style.filter ='';varlast=+newDate();var tick =function(){ opacity +=(newDate()-last)/400; el.style.opacity = opacity; el.style.filter ='alpha(opacity='+(100* opacity)|0+')';last=+newDate();if(opacity <1){(window.requestAnimationFrame && requestAnimationFrame(tick))|| setTimeout(tick,16);}}; tick();} fadeIn(el);// , ,IE9+function fadeIn(el){ el.style.opacity =0;varlast=+newDate();var tick =function(){ el.style.opacity =+el.style.opacity +(newDate()-last)/400;last=+newDate();if(+el.style.opacity <1){(window.requestAnimationFrame && requestAnimationFrame(tick))|| setTimeout(tick,16)}}; tick();} fadeIn(el);// , ,IE10+ el.classList.add('show'); el.classList.remove('hide');.show { transition: opacity 400ms;}.hide { opacity:0;}
Hide
//JQUERY $(el).hide();// , ,IE8+ el.style.display ='none';
Show
//JQUERY $(el).show();// , ,IE8+ el.style.display ='';
//JQUERY $(el).addClass(className);//js// , ,IE8+if(el.classList) el.classList.add(className);else el.className +=' '+ className;// , ,IE10+ el.classList.add(className);
//JQUERY $(el).after(htmlString);//js , ,IE8+ el.insertAdjacentHTML('afterend', htmlString);
//JQUERY $(parent).append(el);//js , ,IE8+ parent.appendChild(el);
//JQUERY $(el).before(htmlString);//js , ,IE8+ el.insertAdjacentHTML('beforebegin', htmlString);
//JQUERY $(el).children();//js// , ,IE8+var children =[];for(var i = el.children.length; i--;){// Skip comment nodes on IE8if(el.children[i].nodeType !=8) children.unshift(el.children[i]);}// , ,IE9+ el.children
//JQUERY $(el).clone();// , ,IE8+ el.cloneNode(true);
//JQUERY $.contains(el, child);// , ,IE8+ el !== child && el.contains(child);
//JQUERY $(el).find(selector).length;// , ,IE8+ el.querySelector(selector)!==null
//JQUERY $(selector).each(function(i, el){});//js , ,IE8+function forEachElement(selector, fn){var elements = document.querySelectorAll(selector);for(var i =0; i < elements.length; i++) fn(elements[i], i);} forEachElement(selector,function(el, i){});//js , ,IE9+var elements = document.querySelectorAll(selector);Array.prototype.forEach.call(elements,function(el, i){});
//JQUERY $(el).empty();//js , ,IE8+while(el.firstChild) el.removeChild(el.firstChild);//js , ,IE9+ el.innerHTML ='';
//JQUERY $(selector).filter(filterFn);// , ,IE8+function filter(selector, filterFn){var elements = document.querySelectorAll(selector);varout=[];for(var i = elements.length; i--;){if(filterFn(elements[i]))out.unshift(elements[i]);}returnout;} filter(selector, filterFn);// , ,IE9+Array.prototype.filter.call(document.querySelectorAll(selector), filterFn);
//JQUERY $(el).find(selector);// , ,IE8+ el.querySelectorAll(selector);
//JQUERY $('.my #awesome selector');// , ,IE8+ document.querySelectorAll('.my #awesome selector');
//JQUERY $(el).attr('tabindex');// , ,IE8+ el.getAttribute('tabindex');
//JQUERY $(el).html();//js el.innerHTML
//JQUERY $(el).css(ruleName);// , ,IE9+ getComputedStyle(el)[ruleName];
//JQUERY $(el).text();// , ,IE8+ el.textContent || el.innerText // , ,IE9+ el.textContent
//JQUERY $(el).hasClass(className);// , ,IE8+if(el.classList) el.classList.contains(className);elsenewRegExp('(^| )'+ className +'( |$)','gi').test(el.className);// , ,IE10+ el.classList.contains(className);
JQUERY $(el).is($(otherEl));//js el === otherEl
//JQUERY $(el).is('.my-class');// , ,IE8+var matches =function(el, selector){var _matches =(el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector);if(_matches){return _matches.call(el, selector);}else{var nodes = el.parentNode.querySelectorAll(selector);for(var i = nodes.length; i--;){if(nodes[i]=== el)returntrue;}returnfalse;}}; matches(el,'.my-class');// , ,IE9+var matches =function(el, selector){return(el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);}; matches(el,'.my-class');
//JQUERY $(el).next();// , ,IE8+// nextSibling can include text nodesfunction nextElementSibling(el){do{ el = el.nextSibling;}while( el && el.nodeType !==1);return el;} el.nextElementSibling || nextElementSibling(el);// , ,IE9+ el.nextElementSibling
//JQUERY $(el).offset();//js , ,IE8+var rect = el.getBoundingClientRect(){ top: rect.top + document.body.scrollTop, left: rect.left + document.body.scrollLeft }
//JQUERY $(el).outerWidth();//js el.offsetWidth
//JQUERY $(el).parent();//js el.parentNode
//JQUERY $(el).position();//js{left: el.offsetLeft, top: el.offsetTop}
//JQUERY $(el).prev();// , ,IE8+// prevSibling can include text nodesfunction previousElementSibling(el){do{ el = el.previousSibling;}while( el && el.nodeType !==1);return el;} el.previousElementSibling || previousElementSibling(el);// , ,IE9+ el.previousElementSibling
//JQUERY $(el).remove();//js , ,IE8+ el.parentNode.removeChild(el);
//JQUERY $(el).removeClass(className);//js , ,IE8+if(el.classList) el.classList.remove(className);else el.className = el.className.replace(newRegExp('(^|\\b)'+ className.split(' ').join('|')+'(\\b|$)','gi'),' ');// , ,IE10+ el.classList.remove(className);
//JQUERY $(el).replaceWith(string);// , ,IE8+ el.outerHTML =string;
//JQUERY $(el).attr('tabindex',3);// , ,IE8+ el.setAttribute('tabindex',3);
//JQUERY $(el).html(string);// , ,IE8+ el.innerHTML =string;
//JQUERY $(el).css('border-width','20px');// , ,IE8+// Use a class if possible el.style.borderWidth ='20px';
//JQUERY $(el).text(string);// , ,IE8+if(el.textContent !==undefined) el.textContent =string;else el.innerText =string;// , ,IE9+ el.textContent =string;
//JQUERY $(el).siblings();// , ,IE8+var siblings =Array.prototype.slice.call(el.parentNode.children);for(var i = siblings.length; i--;){if(siblings[i]=== el){ siblings.splice(i,1);break;}}// , ,IE9+Array.prototype.filter.call(el.parentNode.children,function(child){return child !== el;});
//JQUERY $(el).toggleClass(className);// , ,IE8+if(el.classList){ el.classList.toggle(className);}else{var classes = el.className.split(' ');var existingIndex =-1;for(var i = classes.length; i--;){if(classes[i]=== className) existingIndex = i;}if(existingIndex >=0) classes.splice(existingIndex,1);else classes.push(className); el.className = classes.join(' ');}// , ,IE9+if(el.classList){ el.classList.toggle(className);}else{var classes = el.className.split(' ');var existingIndex = classes.indexOf(className);if(existingIndex >=0) classes.splice(existingIndex,1);else classes.push(className); el.className = classes.join(' ');}// , ,IE10+ el.classList.toggle(className);
//JQUERY $(el).off(eventName, eventHandler);// , ,IE8+function removeEventListener(el, eventName, handler){if(el.removeEventListener) el.removeEventListener(eventName, handler);else el.detachEvent('on'+ eventName, handler);} removeEventListener(el, eventName, handler);// , ,IE9+ el.removeEventListener(eventName, eventHandler);
//JQUERY $(el).on(eventName, eventHandler);// , ,IE8+function addEventListener(el, eventName, handler){if(el.addEventListener){ el.addEventListener(eventName, handler);}else{ el.attachEvent('on'+ eventName,function(){ handler.call(el);});}} addEventListener(el, eventName, handler); , ,IE9+ el.addEventListener(eventName, eventHandler);
//JQUERY $(document).ready(function(){});// , ,IE8+function ready(fn){if(document.readyState !='loading'){ fn();}elseif(document.addEventListener){ document.addEventListener('DOMContentLoaded', fn);}else{ document.attachEvent('onreadystatechange',function(){if(document.readyState !='loading') fn();});}}// , ,IE9+function ready(fn){if(document.readyState !='loading'){ fn();}else{ document.addEventListener('DOMContentLoaded', fn);}
//JQUERY $(el).trigger('my-event',{some:'data'});//js , ,IE9+if(window.CustomEvent){varevent=newCustomEvent('my-event',{detail:{some:'data'}});}else{varevent= document.createEvent('CustomEvent');event.initCustomEvent('my-event',true,true,{some:'data'});} el.dispatchEvent(event);
//JQUERY $(el).trigger('change');// , ,IE8+if(document.createEvent){varevent= document.createEvent('HTMLEvents');event.initEvent('change',true,false); el.dispatchEvent(event);}else{ el.fireEvent('onchange');}// , ,IE9+// For a full list of event types: https://developer.mozilla.org/en-US/docs/Web/API/document.createEventvarevent= document.createEvent('HTMLEvents');event.initEvent('change',true,false); el.dispatchEvent(event);
//JQUERY $.each(array,function(i, item){}); , ,IE8+function forEach(array, fn){for(i =0; i < array.length; i++) fn(array[i], i);} forEach(array,function(item, i){});// , ,IE9+ array.forEach(function(item, i){});
//JQUERY $.extend(true,{}, objA, objB);// , ,IE8+var deepExtend =function(out){out=out||{};for(var i =1; i < arguments.length; i++){var obj = arguments[i];if(!obj)continue;for(var key in obj){if(obj.hasOwnProperty(key)){if(typeof obj[key]==='object') deepExtend(out[key], obj[key]);elseout[key]= obj[key];}}}returnout;}; deepExtend({}, objA, objB);
//JQUERY $.proxy(fn, context);// , ,IE8+ fn.apply(context, arguments);// , ,IE9+ fn.bind(context);
//jQuery $.extend({}, objA, objB);// , ,IE8+var extend =function(out){out=out||{};for(var i =1; i < arguments.length; i++){if(!arguments[i])continue;for(var key in arguments[i]){if(arguments[i].hasOwnProperty(key))out[key]= arguments[i][key];}}returnout;}; extend({}, objA, objB);
//JQUERY $.inArray(item, array);// , ,IE8+function indexOf(array, item){for(var i =0; i < array.length; i++){if(array[i]=== item)return i;}return-1;} indexOf(array, item); , ,IE9+ array.indexOf(item);
//JQUERY $.isArray(arr);// , ,IE8+ isArray =Array.isArray ||function(arr){returnObject.prototype.toString.call(arr)=='[object Array]';} isArray(arr);// , ,IE9+Array.isArray(arr);
//JQUERY $.map(array,function(value, index){});//js , ,IE8+function map(arr, fn){var results =[];for(var i =0; i < arr.length; i++) results.push(fn(arr[i], i));return results;} map(array,function(value, index){});// , ,IE9+ array.map(function(value, index){});
//JQUERY $.now();// , ,IE8+newDate().getTime();// , ,IE9+Date.now();
//JQUERY $.parseHTML(htmlString); , ,IE8+var parseHTML =function(str){var el = document.createElement('div'); el.innerHTML = str;return el.children;}; parseHTML(htmlString); , ,IE9+var parseHTML =function(str){var tmp = document.implementation.createHTMLDocument(); tmp.body.innerHTML = str;return tmp.body.children;}; parseHTML(htmlString);
//JQUERY $.parseJSON(string);// , ,IE8+ JSON.parse(string);
//JQUERY $.trim(string);// , ,IE8+string.replace(/^\s+|\s+$/g,'');// , ,IE9+string.trim();
//JQUERY $.type(obj); , ,IE8+Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/,"$1").toLowerCase();
function reqListener(){var data = JSON.parse(this.responseText); console.log(data);}function reqError(err){ console.log('Fetch Error :-S', err);}var oReq =newXMLHttpRequest(); oReq.onload = reqListener; oReq.onerror = reqError; oReq.open('get','./api/some.json',true); oReq.send();
fetch('./api/some.json').then(function(response){if(response.status !==200){ console.log('Looks like there was a problem. Status Code: '+ response.status);return;}// Examine the text in the response response.json().then(function(data){ console.log(data);});}).catch(function(err){ console.log('Fetch Error :-S', err);});
fetch(url,{ method:'post', headers:{"Content-type":"application/x-www-form-urlencoded; charset=UTF-8"}, body:'foo=bar&lorem=ipsum'}).then(json).then(function(data){ console.log('Request succeeded with JSON response', data);}).catch(function(error){ console.log('Request failed', error);});
fetch(url,{ credentials:'include'})
//JQUERY $.getJSON('/my/url',function(data){});// , ,IE8+var request =newXMLHttpRequest(); request.open('GET','/my/url',true); request.onreadystatechange =function(){if(this.readyState ===4){if(this.status >=200&&this.status <400){// Success!var data = JSON.parse(this.responseText);}else{// Error :(}}}; request.send(); request =null;// , ,IE9+var request =newXMLHttpRequest(); request.open('GET','/my/url',true); request.onload =function(){if(request.status >=200&& request.status <400){// Success!var data = JSON.parse(request.responseText);}else{// We reached our target server, but it returned an error}}; request.onerror =function(){// There was a connection error of some sort}; request.send();// , ,IE10+var request =newXMLHttpRequest(); request.open('GET','/my/url',true); request.onload =function(){if(this.status >=200&&this.status <400){// Success!var data = JSON.parse(this.response);}else{// We reached our target server, but it returned an error}}; request.onerror =function(){// There was a connection error of some sort}; request.send();
//JQUERY $.ajax({ type:'POST', url:'/my/url', data: data });// , ,IE8+var request =newXMLHttpRequest(); request.open('POST','/my/url',true); request.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8'); request.send(data);
//JQUERY $.ajax({ type:'GET', url:'/my/url', success:function(resp){}, error:function(){}});// , ,IE8+var request =newXMLHttpRequest(); request.open('GET','/my/url',true); request.onreadystatechange =function(){if(this.readyState ===4){if(this.status >=200&&this.status <400){// Success!var resp =this.responseText;}else{// Error :(}}}; request.send(); request =null;// , ,IE9+var request =newXMLHttpRequest(); request.open('GET','/my/url',true); request.onload =function(){if(request.status >=200&& request.status <400){// Success!var resp = request.responseText;}else{// We reached our target server, but it returned an error}}; request.onerror =function(){// There was a connection error of some sort}; request.send();// , ,IE10+var request =newXMLHttpRequest(); request.open('GET','/my/url',true); request.onload =function(){if(this.status >=200&&this.status <400){// Success!var resp =this.response;}else{// We reached our target server, but it returned an error}}; request.onerror =function(){// There was a connection error of some sort}; request.send();
//JQUERY $(el).fadeIn();// , ,IE8+function fadeIn(el){var opacity =0; el.style.opacity =0; el.style.filter ='';varlast=+newDate();var tick =function(){ opacity +=(newDate()-last)/400; el.style.opacity = opacity; el.style.filter ='alpha(opacity='+(100* opacity)|0+')';last=+newDate();if(opacity <1){(window.requestAnimationFrame && requestAnimationFrame(tick))|| setTimeout(tick,16);}}; tick();} fadeIn(el);// , ,IE9+function fadeIn(el){ el.style.opacity =0;varlast=+newDate();var tick =function(){ el.style.opacity =+el.style.opacity +(newDate()-last)/400;last=+newDate();if(+el.style.opacity <1){(window.requestAnimationFrame && requestAnimationFrame(tick))|| setTimeout(tick,16)}}; tick();} fadeIn(el);// , ,IE10+ el.classList.add('show'); el.classList.remove('hide');.show { transition: opacity 400ms;}.hide { opacity:0;}
//JQUERY $(el).hide();// , ,IE8+ el.style.display ='none';
//JQUERY $(el).show();// , ,IE8+ el.style.display ='';