jquery iframe 返回上一页_你不需要jQuery
前端發(fā)展很快,現(xiàn)代瀏覽器原生 API 已經(jīng)足夠好用。我們并不需要為了操作 DOM、Event 等再學(xué)習(xí)一下 jQuery 的 API。同時(shí)由于 React、Angular、Vue 等框架的流行,直接操作 DOM 不再是好的模式,jQuery 使用場(chǎng)景大大減少。本項(xiàng)目總結(jié)了大部分 jQuery API 替代的方法,暫時(shí)只支持 IE10 以上瀏覽器。
目錄
Translations
Query Selector
CSS & Style
DOM Manipulation
Ajax
Events
Utilities
Promises
Animation
Alternatives
Browser Support
Query Selector
常用的 class、id、屬性 選擇器都可以使用?document.querySelector?或?document.querySelectorAll?替代。區(qū)別是
document.querySelector?返回第一個(gè)匹配的 Element
document.querySelectorAll?返回所有匹配的 Element 組成的 NodeList。它可以通過(guò)?[].slice.call()?把它轉(zhuǎn)成 Array
如果匹配不到任何 Element,jQuery 返回空數(shù)組?[],但?document.querySelector?返回?null,注意空指針異常。當(dāng)找不到時(shí),也可以使用?||?設(shè)置默認(rèn)的值,如?document.querySelectorAll(selector) || []
注意:document.querySelector?和?document.querySelectorAll?性能很差。如果想提高性能,盡量使用?document.getElementById、document.getElementsByClassName?或?document.getElementsByTagName。
1.0?選擇器查詢
1.1?class 查詢
1.2?id 查詢
1.3?屬性查詢
1.4?后代查詢
1.5?兄弟及上下元素
兄弟元素
上一個(gè)元素
下一個(gè)元素
1.6?Closest
Closest 獲得匹配選擇器的第一個(gè)祖先元素,從當(dāng)前元素開(kāi)始沿 DOM 樹(shù)向上。
// jQuery$el.closest(queryString);// Native - Only latest, NO IEel.closest(selector);// Native - IE10+function closest(el, selector) { const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector; while (el) { if (matchesSelector.call(el, selector)) { return el; } else { el = el.parentElement; } } return null;}1.7?Parents Until
獲取當(dāng)前每一個(gè)匹配元素集的祖先,不包括匹配元素的本身。
// jQuery$el.parentsUntil(selector, filter);// Nativefunction parentsUntil(el, selector, filter) { const result = []; const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector; // match start from parent el = el.parentElement; while (el && !matchesSelector.call(el, selector)) { if (!filter) { result.push(el); } else { if (matchesSelector.call(el, filter)) { result.push(el); } } el = el.parentElement; } return result;}1.8?Form
Input/Textarea
獲取 e.currentTarget 在?.radio?中的數(shù)組索引
1.9?Iframe Contents
jQuery 對(duì)象的 iframe?contents()?返回的是 iframe 內(nèi)的?document
Iframe contents
Iframe Query
1.10?獲取 body
1.11?獲取或設(shè)置屬性
獲取屬性
設(shè)置屬性
獲取?data-?屬性
? 回到頂部
CSS & Style
2.1?CSS
Get style
// jQuery$el.css("color");// Native// 注意:此處為了解決當(dāng) style 值為 auto 時(shí),返回 auto 的問(wèn)題const win = el.ownerDocument.defaultView;// null 的意思是不返回偽類元素win.getComputedStyle(el, null).color;Set style
Get/Set Styles
注意,如果想一次設(shè)置多個(gè) style,可以參考 oui-dom-utils 中?setStyles?方法
Add class
Remove class
has class
Toggle class
2.2?Width & Height
Width 與 Height 獲取方法相同,下面以 Height 為例:
Window height
Document height
Element height
2.3?Position & Offset
Position
獲得匹配元素相對(duì)父元素的偏移
// jQuery$el.position();// Native{ left: el.offsetLeft, top: el.offsetTop }Offset
獲得匹配元素相對(duì)文檔的偏移
// jQuery$el.offset();// Nativefunction getOffset (el) { const box = el.getBoundingClientRect(); return { top: box.top + window.pageYOffset - document.documentElement.clientTop, left: box.left + window.pageXOffset - document.documentElement.clientLeft }}2.4?Scroll Top
獲取元素滾動(dòng)條垂直位置。
// jQuery$(window).scrollTop();// Native(document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;? 回到頂部
DOM Manipulation
3.1?Remove
從 DOM 中移除元素。
// jQuery$el.remove();// Nativeel.parentNode.removeChild(el);3.2?Text
Get text
返回指定元素及其后代的文本內(nèi)容。
// jQuery$el.text();// Nativeel.textContent;Set text
設(shè)置元素的文本內(nèi)容。
// jQuery$el.text(string);// Nativeel.textContent = string;3.3?HTML
Get HTML
Set HTML
3.4?Append
Append 插入到子節(jié)點(diǎn)的末尾
// jQuery$el.append("hello");// Native (HTML string)el.insertAdjacentHTML('beforeend', 'Hello World');// Native (Element)el.appendChild(newEl);3.5?Prepend
3.6?insertBefore
在選中元素前插入新節(jié)點(diǎn)
// jQuery$newEl.insertBefore(queryString);// Native (HTML string)el.insertAdjacentHTML('beforebegin ', 'Hello World');// Native (Element)const el = document.querySelector(selector);if (el.parentNode) { el.parentNode.insertBefore(newEl, el);}3.7?insertAfter
在選中元素后插入新節(jié)點(diǎn)
// jQuery$newEl.insertAfter(queryString);// Native (HTML string)el.insertAdjacentHTML('afterend', 'Hello World');// Native (Element)const el = document.querySelector(selector);if (el.parentNode) { el.parentNode.insertBefore(newEl, el.nextSibling);}3.8?is
如果匹配給定的選擇器,返回true
// jQuery$el.is(selector);// Nativeel.matches(selector);3.9?clone
深拷貝被選元素。(生成被選元素的副本,包含子節(jié)點(diǎn)、文本和屬性。)
//jQuery$el.clone();//Nativeel.cloneNode(); //深拷貝添加參數(shù)‘true’ ```3.10?empty
移除所有子節(jié)點(diǎn)
//jQuery$el.empty();//Nativeel.innerHTML = '';3.11?wrap
把每個(gè)被選元素放置在指定的HTML結(jié)構(gòu)中。
//jQuery$(".inner").wrap(');//NativeArray.prototype.forEach.call(document.querySelector('.inner'), (el) => { const wrapper = document.createElement('div'); wrapper.className = 'wrapper'; el.parentNode.insertBefore(wrapper, el); el.parentNode.removeChild(el); wrapper.appendChild(el);});3.12?unwrap
移除被選元素的父元素的DOM結(jié)構(gòu)
// jQuery$('.inner').unwrap();// NativeArray.prototype.forEach.call(document.querySelectorAll('.inner'), (el) => { let elParentNode = el.parentNode if(elParentNode !== document.body) { elParentNode.parentNode.insertBefore(el, elParentNode) elParentNode.parentNode.removeChild(elParentNode) }});3.13?replaceWith
用指定的元素替換被選的元素
//jQuery$('.inner').replaceWith(');//NativeArray.prototype.forEach.call(document.querySelectorAll('.inner'),(el) => { const outer = document.createElement("div"); outer.className = "outer"; el.parentNode.insertBefore(outer, el); el.parentNode.removeChild(el);});3.14?simple parse
?解析 HTML/SVG/XML 字符串
// jQuery$(`<ol> <li>ali> <li>bli>ol><ol> <li>cli> <li>dli>ol>`);// Nativerange = document.createRange();parse = range.createContextualFragment.bind(range);parse(`<ol> <li>ali> <li>bli>ol><ol> <li>cli> <li>dli>ol>`);? 回到頂部
Ajax
Fetch API?是用于替換 XMLHttpRequest 處理 ajax 的新標(biāo)準(zhǔn),Chrome 和 Firefox 均支持,舊瀏覽器可以使用 polyfills 提供支持。
IE9+ 請(qǐng)使用?github/fetch,IE8+ 請(qǐng)使用?fetch-ie8,JSONP 請(qǐng)使用?fetch-jsonp。
4.1?從服務(wù)器讀取數(shù)據(jù)并替換匹配元素的內(nèi)容。
? 回到頂部
Events
完整地替代命名空間和事件代理,鏈接到?https://github.com/oneuijs/oui-dom-events
5.0?Document ready by?DOMContentLoaded
5.1?使用 on 綁定事件
5.2?使用 off 解綁事件
5.3?Trigger
? 回到頂部
Utilities
大部分實(shí)用工具都能在 native API 中找到. 其他高級(jí)功能可以選用專注于該領(lǐng)域的穩(wěn)定性和性能都更好的庫(kù)來(lái)代替,推薦?lodash。
6.1?基本工具
isArray
檢測(cè)參數(shù)是不是數(shù)組。
// jQuery$.isArray(range);// NativeArray.isArray(range);isWindow
檢測(cè)參數(shù)是不是 window。
// jQuery$.isWindow(obj);// Nativefunction isWindow(obj) { return obj !== null && obj !== undefined && obj === obj.window;}inArray
在數(shù)組中搜索指定值并返回索引 (找不到則返回 -1)。
// jQuery$.inArray(item, array);// Nativearray.indexOf(item) > -1;// ES6-wayarray.includes(item);isNumeric
檢測(cè)傳入的參數(shù)是不是數(shù)字。 Use?typeof?to decide the type or the?type?example for better accuracy.
// jQuery$.isNumeric(item);// Nativefunction isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n);}isFunction
檢測(cè)傳入的參數(shù)是不是 JavaScript 函數(shù)對(duì)象。
// jQuery$.isFunction(item);// Natifunction isFunction(item) { if (typeof item === 'function') { return true; } var type = Object.prototype.toString(item); return type === '[object Function]' || type === '[object GeneratorFunction]';}isEmptyObject
檢測(cè)對(duì)象是否為空 (包括不可枚舉屬性).
// jQuery$.isEmptyObject(obj);// Nativefunction isEmptyObject(obj) { return Object.keys(obj).length === 0;}isPlainObject
檢測(cè)是不是扁平對(duì)象 (使用 “{}” 或 “new Object” 創(chuàng)建).
// jQuery$.isPlainObject(obj);// Nativefunction isPlainObject(obj) { if (typeof (obj) !== 'object' || obj.nodeType || obj !== null && obj !== undefined && obj === obj.window) { return false; } if (obj.constructor && !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) { return false; } return true;}extend
合并多個(gè)對(duì)象的內(nèi)容到第一個(gè)對(duì)象。 object.assign 是 ES6 API,也可以使用?polyfill。
// jQuery$.extend({}, defaultOpts, opts);// NativeObject.assign({}, defaultOpts, opts);trim
移除字符串頭尾空白。
// jQuery$.trim(string);// Nativestring.trim();map
將數(shù)組或?qū)ο筠D(zhuǎn)化為包含新內(nèi)容的數(shù)組。
// jQuery$.map(array, (value, index) => {});// Nativearray.map((value, index) => {});each
輪詢函數(shù),可用于平滑的輪詢對(duì)象和數(shù)組。
// jQuery$.each(array, (index, value) => {});// Nativearray.forEach((value, index) => {});grep
找到數(shù)組中符合過(guò)濾函數(shù)的元素。
// jQuery$.grep(array, (value, index) => {});// Nativearray.filter((value, index) => {});type
檢測(cè)對(duì)象的 JavaScript [Class] 內(nèi)部類型。
// jQuery$.type(obj);// Nativefunction type(item) { const reTypeOf = /(?:^\[object\s(.*?)\]$)/; return Object.prototype.toString.call(item) .replace(reTypeOf, '$1') .toLowerCase();}merge
合并第二個(gè)數(shù)組內(nèi)容到第一個(gè)數(shù)組。
// jQuery$.merge(array1, array2);// Native// 使用 concat,不能去除重復(fù)值function merge(...args) { return [].concat(...args)}// ES6,同樣不能去除重復(fù)值array1 = [...array1, ...array2]// 使用 Set,可以去除重復(fù)值function merge(...args) { return Array.from(new Set([].concat(...args)))}now
返回當(dāng)前時(shí)間的數(shù)字呈現(xiàn)。
// jQuery$.now();// NativeDate.now();proxy
傳入函數(shù)并返回一個(gè)新函數(shù),該函數(shù)綁定指定上下文。
// jQuery$.proxy(fn, context);// Nativefn.bind(context);// jQuery$.proxy(fn, context);// Nativefn.bind(context);makeArray
類數(shù)組對(duì)象轉(zhuǎn)化為真正的 JavaScript 數(shù)組。
// jQuery$.makeArray(arrayLike);// NativeArray.prototype.slice.call(arrayLike);// ES6-wayArray.from(arrayLike);6.2?包含
檢測(cè) DOM 元素是不是其他 DOM 元素的后代.
// jQuery$.contains(el, child);// Nativeel !== child && el.contains(child);6.3?Globaleval
全局執(zhí)行 JavaScript 代碼。
// jQuery$.globaleval(code);// Nativefunction Globaleval(code) { const script = document.createElement('script'); script.text = code; document.head.appendChild(script).parentNode.removeChild(script);}// Use eval, but context of eval is current, context of $.Globaleval is global.eval(code);?解析
6.4 parseHTML
解析字符串為 DOM 節(jié)點(diǎn)數(shù)組.
// jQuery$.parseHTML(htmlString);// Nativefunction parseHTML(string) {const context = document.implementation.createHTMLDocument();// Set the base href for the created document so any parsed elements with URLs// are based on the document's URLconst base = context.createElement('base');base.href = document.location.href;context.head.appendChild(base);context.body.innerHTML = string;return context.body.children;}
parseJSON
傳入格式正確的 JSON 字符串并返回 JavaScript 值.
// jQuery$.parseJSON(str);// NativeJSON.parse(str);?回到頂部
Promises
Promise 代表異步操作的最終結(jié)果。jQuery 用它自己的方式處理 promises,原生 JavaScript 遵循?Promises/A+?標(biāo)準(zhǔn)實(shí)現(xiàn)了最小 API 來(lái)處理 promises。
7.1?done, fail, always
done?會(huì)在 promise 解決時(shí)調(diào)用,fail?會(huì)在 promise 拒絕時(shí)調(diào)用,always?總會(huì)調(diào)用。
// jQuery$promise.done(doneCallback).fail(failCallback).always(alwaysCallback)// Nativepromise.then(doneCallback, failCallback).then(alwaysCallback, alwaysCallback)7.2?when
when?用于處理多個(gè) promises。當(dāng)全部 promises 被解決時(shí)返回,當(dāng)任一 promise 被拒絕時(shí)拒絕。
// jQuery$.when($promise1, $promise2).done((promise1Result, promise2Result) => {});// NativePromise.all([$promise1, $promise2]).then([promise1Result, promise2Result] => {});
7.3?Deferred
Deferred 是創(chuàng)建 promises 的一種方式。
// jQueryfunction asyncFunc() { const defer = new $.Deferred(); setTimeout(() => { if(true) { defer.resolve('some_value_computed_asynchronously'); } else { defer.reject('failed'); } }, 1000); return defer.promise();}// Nativefunction asyncFunc() { return new Promise((resolve, reject) => { setTimeout(() => { if (true) { resolve('some_value_computed_asynchronously'); } else { reject('failed'); } }, 1000); });}// Deferred wayfunction defer() { const deferred = {}; const promise = new Promise((resolve, reject) => { deferred.resolve = resolve; deferred.reject = reject; }); deferred.promise = () => { return promise; }; return deferred;}function asyncFunc() { const defer = defer(); setTimeout(() => { if(true) { defer.resolve('some_value_computed_asynchronously'); } else { defer.reject('failed'); } }, 1000); return defer.promise();}? 回到頂部
Animation
8.1?Show & Hide
8.2?Toggle
顯示或隱藏元素。
// jQuery$el.toggle();// Nativeif (el.ownerDocument.defaultView.getComputedStyle(el, null).display === 'none') { el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block';} else { el.style.display = 'none';}8.3?FadeIn & FadeOut
8.4?FadeTo
調(diào)整元素透明度。
// jQuery$el.fadeTo('slow',0.15);// Nativeel.style.transition = 'opacity 3s'; // 假設(shè) 'slow' 等于 3 秒el.style.opacity = '0.15';8.5?FadeToggle
動(dòng)畫調(diào)整透明度用來(lái)顯示或隱藏。
// jQuery$el.fadeToggle();// Nativeel.style.transition = 'opacity 3s';const { opacity } = el.ownerDocument.defaultView.getComputedStyle(el, null);if (opacity === '1') { el.style.opacity = '0';} else { el.style.opacity = '1';}8.6?SlideUp & SlideDown
8.7?SlideToggle
滑動(dòng)切換顯示或隱藏。
// jQuery$el.slideToggle();// Nativeconst originHeight = '100px';el.style.transition = 'height 3s';const { height } = el.ownerDocument.defaultView.getComputedStyle(el, null);if (parseInt(height, 10) === 0) { el.style.height = originHeight;}else { el.style.height = '0px';}8.8?Animate
執(zhí)行一系列 CSS 屬性動(dòng)畫。
// jQuery$el.animate({ params }, speed);// Nativeel.style.transition = 'all ' + speed;Object.keys(params).forEach((key) => el.style[key] = params[key];)替代品
你可能不需要 jQuery (You Might Not Need jQuery)?- 如何使用原生 JavaScript 實(shí)現(xiàn)通用事件,元素,ajax 等用法。
npm-dom?以及?webmodules?- 在 NPM 上提供獨(dú)立 DOM 模塊的組織
瀏覽器支持程序
許可證
MIT
英文原文:https://github.com/nefe/You-Dont-Need-jQuery/blob/master/README.zh-CN.md總結(jié)
以上是生活随笔為你收集整理的jquery iframe 返回上一页_你不需要jQuery的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 中国科大实现量子增强的微波测距
- 下一篇: 是不是一个东西_迷你世界:一个金币就能买