oneuijs/You-Dont-Need-jQuery

oneuijs/You-Dont-Need-jQuery

https://github.com/oneuijs/You-Dont-Need-jQuery/blob/master/README.zh-CN.md

You Don't Need jQuery

前端發展很快,現代瀏覽器原生 API 已經足夠好用。我們并不需要為了操作 DOM、Event 等再學習一下 jQuery 的 API。同時由于 React、Angular、Vue 等框架的流行,直接操作 DOM 不再是好的模式,jQuery 使用場景大大減少。本項目總結了大部分 jQuery API 替代的方法,暫時只支持 IE10+ 以上瀏覽器。

Translations

Query Selector

常用的 class、id、屬性 選擇器都可以使用?document.querySelector?或?document.querySelectorAll?替代。區別是

  • document.querySelector?返回第一個匹配的 Element
  • document.querySelectorAll?返回所有匹配的 Element 組成的 NodeList。它可以通過?[].slice.call()?把它轉成 Array
  • 如果匹配不到任何 Element,jQuery 返回空數組?[],但?document.querySelector?返回?null,注意空指針異常。當找不到時,也可以使用?||?設置默認的值,如?document.querySelectorAll(selector) || []

注意:document.querySelector?和?document.querySelectorAll?性能很。如果想提高性能,盡量使用?document.getElementByIddocument.getElementsByClassName?或?document.getElementsByTagName

  • 1.0?Query by selector

    // jQuery
    (selector);// Native
    document.querySelectorAll(selector);
  • 1.1?Query by class

    // jQuery
    ();// Native
    document.querySelectorAll();document.getElementsByClassName();
  • 1.2?Query by id

    // jQuery
    ();// Native
    document.querySelector();document.getElementById();
  • 1.3?Query by attribute

    // jQuery
    (a[target=_blank]);// Native
    document.querySelectorAll(a[target=_blank]);
  • 1.4?Find sth.

    • Find nodes

      // jQuery
      .();// Native
      .querySelectorAll();
    • Find body

      // jQuery
      ();// Native
      document.;
    • Find Attribute

      // jQuery
      .();// Native
      .getAttribute();
    • Find data attribute

      // jQuery
      .();// Native
      // using getAttribute
      .getAttribute(data-foo);
      // you can also use `dataset` if only need to support IE 11+
      .dataset[];
  • 1.5?Sibling/Previous/Next Elements

    • Sibling elements

      // jQuery
      .siblings();// Native
      [].filter.(.parentNode.children, function(child) {return child  el;
      });
    • Previous elements

      // jQuery
      .();// Native
      .previousElementSibling;
      
    • Next elements

      // next
      .();
      .nextElementSibling;
  • 1.6?Closest

    Closest 獲得匹配選擇器的第一個祖先元素,從當前元素開始沿 DOM 樹向上。

    // jQuery
    .closest(queryString);// Native
    function closest(, selector) {const matchesSelector  .matches  .webkitMatchesSelector  .mozMatchesSelector  .msMatchesSelector;while (el) {(matchesSelector.(el, selector)) {return el;}  {el  .parentElement;}}return ;
    }
  • 1.7?Parents Until

    獲取當前每一個匹配元素集的祖先,不包括匹配元素的本身。

    // jQuery
    .parentsUntil(selector, filter);// Native
    function parentsUntil(, selector, filter) {const result  [];const matchesSelector  .matches  .webkitMatchesSelector  .mozMatchesSelector  .msMatchesSelector;// match start from parentel  .parentElement;while (el  matchesSelector.(el, selector)) {(filter) {result.(el);}  {(matchesSelector.(el, filter)) {result.(el);}}el  .parentElement;}return result;
    }
  • 1.8?Form

    • Input/Textarea

      // jQuery
      (#my-input).();// Native
      document.querySelector(#my-input).value;
    • Get index of e.currentTarget between?.radio

      // jQuery
      (.currentTarget).index(.radio);// Native
      [].indexOf.(document.querySelectorAll(.radio), .currentTarget);
  • 1.9?Iframe Contents

    jQuery 對象的 iframe?contents()?返回的是 iframe 內的?document

    • Iframe contents

      // jQuery
      $iframe.contents();// Native
      iframe.contentDocument;
    • Iframe Query

      // jQuery
      $iframe.contents().();// Native
      iframe.contentDocument.querySelectorAll();

? 回到頂部

CSS & Style

  • 2.1?CSS

    • Get style

      // jQuery
      .(color);// Native
      // 注意:此處為了解決當 style 值為 auto 時,返回 auto 的問題
      const   .ownerDocument.defaultView;
      // null 的意思是不返回偽類元素
      .getComputedStyle(el, ).color;
    • Set style

      // jQuery
      .({ color #ff0011 });// Native
      .style.color  #ff0011;
    • Get/Set Styles

      注意,如果想一次設置多個 style,可以參考 oui-dom-utils 中?setStyles?方法

    • Add class

      // jQuery
      .addClass(className);// Native
      .classList.(className);
    • Remove class

      // jQuery
      .removeClass(className);// Native
      .classList.remove(className);
    • has class

      // jQuery
      .hasClass(className);// Native
      .classList.contains(className);
    • Toggle class

      // jQuery
      .toggleClass(className);// Native
      .classList.toggle(className);
  • 2.2?Width & Height

    Width 與 Height 獲取方法相同,下面以 Height 為例:

    • Window height

      // jQuery
      (window).height();// Native
      // 不含 scrollbar,與 jQuery 行為一致
      window.document.documentElement.clientHeight;
      // 含 scrollbar
      window.innerHeight;
    • Document height

      // jQuery
      (document).height();// Native
      document.documentElement.scrollHeight;
    • Element height

      // jQuery
      .height();// Native
      // 與 jQuery 一致(一直為 content 區域的高度)
      function getHeight() {const styles  .getComputedStyle(el);const height  .offsetHeight;const borderTopWidth  parseFloat(styles.borderTopWidth);const borderBottomWidth  parseFloat(styles.borderBottomWidth);const paddingTop  parseFloat(styles.paddingTop);const paddingBottom  parseFloat(styles.paddingBottom);return height  borderBottomWidth  borderTopWidth  paddingTop  paddingBottom;
      }
      // 精確到整數(border-box 時為 height 值,content-box 時為 height + padding + border 值)
      .clientHeight;
      // 精確到小數(border-box 時為 height 值,content-box 時為 height + padding + border 值)
      .getBoundingClientRect().height;
    • Iframe height

      $iframe .contents() 方法返回 iframe 的 contentDocument

      // jQuery
      (iframe).contents().height();// Native
      iframe.contentDocument.documentElement.scrollHeight;
  • 2.3?Position & Offset

    • Position

      // jQuery
      .position();// Native
      { left .offsetLeft, top .offsetTop }
    • Offset

      // jQuery
      .offset();// Native
      function getOffset () {const   .getBoundingClientRect();return {top .  window.pageYOffset  document.documentElement.clientTop,left .  window.pageXOffset  document.documentElement.clientLeft}
      }
  • 2.4?Scroll Top

    // jQuery
    (window).scrollTop();// Native
    (document.documentElement  document.documentElement.scrollTop)  document..scrollTop;

? 回到頂部

DOM Manipulation

  • 3.1?Remove

    // jQuery
    .remove();// Native
    .parentNode.removeChild(el);
  • 3.2?Text

    • Get text

      // jQuery
      .();// Native
      .textContent;
    • Set text

      // jQuery
      .(string);// Native
      .textContent  string;
  • 3.3?HTML

    • Get HTML

      // jQuery
      .();// Native
      .innerHTML;
    • Set HTML

      // jQuery
      .(htmlString);// Native
      .innerHTML  htmlString;
  • 3.4?Append

    Append 插入到子節點的末尾

    // jQuery
    .append(<div id='container'>hello</div>);// NativenewEl  document.createElement();
    newEl.setAttribute(, container);
    newEl.innerHTML  hello;
    .appendChild(newEl);
  • 3.5?Prepend

    // jQuery
    .prepend(<div id='container'>hello</div>);// NativenewEl  document.createElement();
    newEl.setAttribute(, container);
    newEl.innerHTML  hello;
    .insertBefore(newEl, .firstChild);
  • 3.6?insertBefore

    在選中元素前插入新節點

    // jQuery
    $newEl.insertBefore(queryString);// Native
    const target  document.querySelector(queryString);
    target.parentNode.insertBefore(newEl, target);
  • 3.7?insertAfter

    在選中元素后插入新節點

    // jQuery
    $newEl.insertAfter(queryString);// Native
    const target  document.querySelector(queryString);
    target.parentNode.insertBefore(newEl, target.nextSibling);

? 回到頂部

用?fetch?和?fetch-jsonp?替代

? 回到頂部

Events

完整地替代命名空間和事件代理,鏈接到?https://github.com/oneuijs/oui-dom-events

  • 5.1?Bind an event with on

    // jQuery
    .(eventName, eventHandler);// Native
    .addEventListener(eventName, eventHandler);
  • 5.2?Unbind an event with off

    // jQuery
    .(eventName, eventHandler);// Native
    .removeEventListener(eventName, eventHandler);
  • 5.3?Trigger

    // jQuery
    (el).trigger(custom-event, {key1 });// Native(window.CustomEvent) {const event   CustomEvent(custom-event, {detail {key1 }});
    }  {const event  document.createEvent(CustomEvent);event.initCustomEvent(custom-event, , , {key1 });
    }.dispatchEvent(event);

? 回到頂部

Utilities

  • 6.1?isArray

    // jQuery
    .isArray(range);// Native
    Array.isArray(range);
  • 6.2?Trim

    // jQuery
    .(string);// Native
    string.();
  • 6.3?Object Assign

    繼承,使用 object.assign polyfill?https://github.com/ljharb/object.assign

    // jQuery
    .extend({}, defaultOpts, opts);// Native
    Object.assign({}, defaultOpts, opts);
  • 6.4?Contains

    // jQuery
    .contains(el, child);// Native
    el  child  .contains(child);

? 回到頂部

Alternatives

  • 你可能不需要 jQuery (You Might Not Need jQuery)?- 如何使用原生 JavaScript 實現通用事件,元素,ajax 等用法。
  • npm-dom?以及?webmodules?- 在 NPM 上提供獨立 DOM 模塊的組織

Browser Support

Latest ?Latest ?10+ ?Latest ?6.1+ ?

License

轉載于:https://www.cnblogs.com/WhiteHorseIsNotHorse/p/6137041.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/457440.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/457440.shtml
英文地址,請注明出處:http://en.pswp.cn/news/457440.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Wpf 數據綁定簡介、實例1

簡介&#xff1a;1.WPF綁定使用的源屬性必須是依賴項屬性&#xff0c;這是因為依賴項屬性具有內置的更改通知支持&#xff0c;元素綁定表達式使用了Xaml擴展標記&#xff0c; WPF綁定一個控件是使用Binding.ElementName, 綁定非控件對象時使用Source,RelativeSource,DataContex…

【設計模式 04】代理模式

代理模式 代理模式( Proxy)&#xff1a;為其他對象提供一種代理以控制對這個對象的訪問。 參考&#xff1a;refactoringguru | proxy 什么是代理模式 有時候如果想要訪問某個對象&#xff0c;但又沒辦法直接訪問或不方便直接訪問&#xff0c;可以使用代理模式&#xff0c;代理…

css 大于號 標簽_CSS設計基礎選擇器篇

點擊上方 Java項目學習 &#xff0c;選擇 星標 公眾號重磅資訊、干貨&#xff0c;第一時間送達前言&#xff1a;如果將CSS樣式應用于特定的網頁對象上&#xff0c;需要先找到目標元素。在CSS樣式中執行這一任務的部分被稱為選擇器。1 標簽選擇器優點&#xff1a;為頁面中同類型…

CSDN博客投票活動開始了

自己堅持寫博客&#xff0c;一方面是為了將自己對知識點的理解做一個總結&#xff0c;另一方面也是因為自己看到了很多無私奉獻分享自己知識的小伙伴們&#xff0c;因此自己也想像他們那樣盡自己微薄之力把自己對某一知識點的理解分享給大家&#xff0c;或許算不上什么特高級的…

crontab 提示 command not found 解決方案

crontab 提示 command not found 解決方案 今天遇見一個問題&#xff0c;crontab的定時任務會報錯&#xff1a;java command not found&#xff0c;但是手動執行腳本一直能成功。 猜想是環境變量的問題。 在crontab里添加個打印環境變量的任務&#xff1a; * * * * * echo $PAT…

java中文亂碼decode_Java中文亂碼處理

java編碼轉換過程我們總是用一個java類文件和用戶進行最直接的交互(輸入、輸出)&#xff0c;這些交互內容包含的文字可能會包含中文。無論這些java類是與數據庫交互&#xff0c;還是與前端頁面交互&#xff0c;他們的生命周期總是這樣的&#xff1a;1、程序員在操作系統上通過編…

【設計模式 05】工廠方法模式

工廠方法模式 define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. 參考&#xff1a; refactoringguru | factory-methodjavatpoint | factory-method-design-pattern博客園| 工廠方法 簡單工廠的問題 …

[C++]宏定義#define A B C

C關于宏定義的用法&#xff0c;有形如#define A B C的格式&#xff0c;此時B和C都是已知的字符串常量. 在宏定義中. 可以把兩個常量字符串連在一起 如果#define A "a" 那么宏定義#define STRING A "bc" 就相當于 #define STRING "abc" 這里&…

LinkedList類源碼淺析(二)

1、上一節介紹了LinkedList的幾個基本的方法&#xff0c;其他方法類似&#xff0c;就不一一介紹&#xff1b; 現在再來看一個刪除的方法&#xff1a;remove(Object o) remove方法接受一個Object參數&#xff0c;這里需要對參數做空與非空處理&#xff1b; 但是刪除一個Object元…

【設計模式 06】原型模式(克隆??)

原型模式(clone?) Prototype pattern refers to creating duplicate object while keeping performance in mind. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. 參考&#xff1a; tutori…

2016OSC源創會年終盛典-綜合技術專場-張小剛

2019獨角獸企業重金招聘Python工程師標準>>> 綜合技術專場 講師/SPEAKERS 張小剛 網易云負載均衡項目負責人 《網易蜂巢負載均衡技術實踐》從網易蜂巢中的實踐出發&#xff0c;分享網易蜂巢負載均衡服務從無到有&#xff0c;從私有云到公有云過程中的技術實踐。重點…

python策略模式包含角色_詳解Python設計模式之策略模式

雖然設計模式與語言無關&#xff0c;但這并不意味著每一個模式都能在每一門語言中使用。《設計模式&#xff1a;可復用面向對象軟件的基礎》一書中有 23 個模式&#xff0c;其中有 16 個在動態語言中“不見了&#xff0c;或者簡化了”。1、策略模式概述策略模式&#xff1a;定義…

mysql 日期

數據類型 數據類型格式date YYYY-MM-DD datetime YYYY-MM-DD HH:MM:SS timestamp YYYY-MM-DD HH:MM:SS year YYYY 或 YY 具體實現的函數 1、now() 返回當前的日期和時間 SELECT NOW(); 2、curdate() 返回當前的日期 SELECT CURdate(); 3、curtime&#xff08;&#xff09;返回當…

【Go】panic: reflect: call of reflect.Value.FieldByName on ptr Value

產生原因 調用 FieldByName()方法時&#xff0c;調用者與預期類型不相符。 // 錯誤代碼 func setNewArticleInfoToCache(article *Article) {fields : []string{"Title", "Abstract", "ID", "AuthorID", "CreateTime",}im…

超完整的 Chrome 瀏覽器客戶端調試大全

2019獨角獸企業重金招聘Python工程師標準>>> 引言 “工欲善其事&#xff0c;必先利其器” 沒錯&#xff0c;這句話個人覺得說的特別有道理&#xff0c;舉個例子來說吧&#xff0c;厲害的化妝師都有一套非常專業的刷子&#xff0c;散粉刷負責定妝&#xff0c;眼影刷負…

PHP 獲取服務器詳細信息【轉】

碰到此問題&#xff0c;做下記錄 獲取系統類型及版本號&#xff1a; php_uname() (例&#xff1a;Windows NT COMPUTER 5.1 build 2600)只獲取系統類型&#xff1a; php_uname(s) (或&#xff1…

HIVE攻略 JFK_Hive安裝及使用攻略

目錄Hive的安裝Hive的基本使用:CRUDHive交互式模式數據導入數據導出Hive查詢HiveQLHive視圖Hive分區表1. Hive的安裝系統環境裝好hadoop的環境后&#xff0c;我們可以把Hive裝在namenode機器上(c1)。hadoop的環境&#xff0c;請參考&#xff1a;讓Hadoop跑在云端系列文章&#…

MySQL 為什么用索引,為什么是 B+樹,怎么用索引

MySQL 索引 A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records. 為什么需要索…

頁面加載完畢執行多個JS函數

通常我們需要在打開頁面時加載腳本&#xff0c;這些腳本必須在頁面加載完畢后才可以執行&#xff0c;因為這時候DOM才完整&#xff0c;可以利用window.onload確保這一點&#xff0c;如&#xff1a;window.οnlοadfirstFunction;這腳本的意思是在頁面完畢后執行firstFunction函…

Servlet 生命周期、工作原理

Servlet 生命周期&#xff1a;Servlet 加載--->實例化--->服務--->銷毀。init&#xff08;&#xff09;&#xff1a;在Servlet的生命周期中&#xff0c;僅執行一次init()方法。它是在服務器裝入Servlet時執行的&#xff0c;負責初始化Servlet對象。可以配置服務器&…