[教學] 越來越像 jQuery 的原生 JavaScript

看板Ajax作者 (吉米林)時間6年前 (2017/08/07 21:55), 編輯推噓4(406)
留言10則, 4人參與, 最新討論串1/1
https://dom.spec.whatwg.org/#interface-childnode DOM manipulation convenience methods 是 WHATWG 的 Living Standard, 提供更接近 jQuery 用法的 DOM API。 【移除】 jQuery: $('.someClass').remove(); 原生: document.querySelector('.someClass').remove(); 【Prepend】 jQuery: $('.someClass').prepend('hello world'); 原生: document.querySelector('.someClass').prepend('hello world'); 【Append】 jQuery: $('.someClass').append('hello world'); 原生: document.querySelector('.someClass').append('hello world'); 【Before】 jQuery: $('.someClass').before('hello world'); 原生: document.querySelector('.someClass').before('hello world'); 【After】 jQuery: $('.someClass').after('hello world'); 原生: document.querySelector('.someClass').after('hello world'); 【取代】 jQuery: $('.someClass').replaceWith(element); 原生: document.querySelector('.someClass').replaceWith(element); 【For-Loop 所有相符的元素】 jQuery: $('.someClass').each(function () { ... }); 原生: document.querySelectorAll('.someClass').forEach(element => { ... }) (NodeList 可以直接 forEach() 了。) 【瀏覽器支援程度】 除了 IE 和 Edge 外其他主流瀏覽器的最新版本都 OK。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.224.8.107 ※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1502114119.A.552.html

08/07 22:52, , 1F
說到 each, 我對 jQuery 的 each 跟原生 JS 的 forEach
08/07 22:52, 1F

08/07 22:53, , 2F
callback 的參數順序不一樣感覺各種囧...
08/07 22:53, 2F

08/07 22:53, , 3F
jQuery 的 each 是 (index, element)=>...
08/07 22:53, 3F

08/07 22:54, , 4F
原生 JS 的 forEach 是 (element, index) => ...
08/07 22:54, 4F

08/09 14:31, , 5F
element 先比較符合傳統
08/09 14:31, 5F

08/09 14:32, , 6F
因為 Array.map() 也是先 value 才 index
08/09 14:32, 6F

08/09 14:34, , 7F
IE不支援就算了,Edge 不支援比較麻煩
08/09 14:34, 7F

08/14 09:22, , 8F
繼續努力,讓不能用的都可以用吧
08/14 09:22, 8F

09/08 00:42, , 9F
append 和 appendChild 不一樣也蠻冏的
09/08 00:42, 9F

09/13 11:10, , 10F
請持續努力直到作出下一個jQuerylite
09/13 11:10, 10F
文章代碼(AID): #1PY757LI (Ajax)