oneuijs/You-Dont-Need-jQuery

來源:互聯網
上載者:User

標籤:read   替代   app   call   attr   trim   webkit   json   first   

oneuijs/You-Dont-Need-jQuery https://github.com/oneuijs/You-Dont-Need-jQuery/blob/master/README.zh-CN.mdYou Don‘t Need jQuery

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

TranslationsQuery Selector

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

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

注意:document.querySelector 和 document.querySelectorAll 效能很差。如果想提高效能,盡量使用 document.getElementById、document.getElementsByClassName 或 document.getElementsByTagName。

  • 1.0 Query by selector

    // jQuery(selector);// Nativedocument.querySelectorAll(selector);
  • 1.1 Query by class

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

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

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

    • Find nodes

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

      // jQuery();// Nativedocument.;
    • 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);// Nativefunction 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);// Nativefunction parentsUntil(, selector, filter) {  const result  [];  const matchesSelector  .matches  .webkitMatchesSelector  .mozMatchesSelector  .msMatchesSelector;  // match start from parent  el  .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).();// Nativedocument.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();// Nativeiframe.contentDocument;
    • Iframe Query

      // jQuery$iframe.contents().();// Nativeiframe.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;// 含 scrollbarwindow.innerHeight;
    • Document height

      // jQuery(document).height();// Nativedocument.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();// Nativeiframe.contentDocument.documentElement.scrollHeight;
  • 2.3 Position & Offset

    • Position

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

      // jQuery.offset();// Nativefunction 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>);// Native newEl  document.createElement();newEl.setAttribute(, container);newEl.innerHTML  hello;.appendChild(newEl);
  • 3.5 Prepend

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

    在選中元素前插入新節點

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

    在選中元素後插入新節點

    // jQuery$newEl.insertAfter(queryString);// Nativeconst 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);// NativeArray.isArray(range);
  • 6.2 Trim

    // jQuery.(string);// Nativestring.();
  • 6.3 Object Assign

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

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

    // jQuery.contains(el, child);// Nativeel  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

oneuijs/You-Dont-Need-jQuery

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.