jQuery 本質上是 JavaScript 的一層包裝,目的就一句話:用更少的 code,把更多事情做完。但如果原生 API 已經能做,多載一個 80KB 的庫是否值得,就該重新評估了。以下把常見操作並排比較,方便你判斷哪些還需要 jQuery。
原生 window.onload 有個眾所皆知的問題:同一頁面只能指派一個,後寫的會蓋掉前面的。
window.onload = first;
window.onload = second; // first 不會執行
// 得改成這樣才行
window.onload = function () {
first();
second();
};
jQuery 的 ready 可以寫多段,全部執行:
$(document).ready(function () { first(); });
$(document).ready(function () { second(); });
原生的對等寫法是 document.addEventListener("DOMContentLoaded", first),用事件監聽就能有多個處理器,本質上和 jQuery 一樣。
document.getElementById('idName') // 原生
$('#idName') // jQuery
document.getElementsByClassName('cls') // 原生(無 IE8 以下支援)
$('.className') // jQuery
document.getElementsByTagName('tag') // 原生
$('tag') // jQuery
document.querySelectorAll('.a .b') // 原生萬用選擇器
$('.a .b') // jQuery
原生沒有預設的「用 class 選取」寫法這句話,在 querySelectorAll 問世後已經不成立了。
// 原生
var para = document.createElement('p');
document.body.appendChild(para); // 追加為最後一個子節點
// jQuery 提供 append / appendTo / prepend / prependTo
$('p').append('<b>Hello!</b>'); // <p>World!<b>Hello!</b></p>
$('<b>Hello!</b>').appendTo('p'); // 同上
$('p').prepend('<b>Hello!</b>'); // <p><b>Hello!</b>World!</p>
$('<b>Hello!</b>').prependTo('p'); // 同上
// 原生 insertBefore
parentElement.insertBefore(newElement, targetElement);
var imgs = document.getElementById('imgs');
var para = document.getElementsByTagName('p')[0];
para.parentNode.insertBefore(imgs, para);
// jQuery 提供 after / insertAfter / before / insertBefore
$('p').after('<b>Hello!</b>'); // <p>World!</p><b>Hello!</b>
$('<b>Hello!</b>').insertAfter('p'); // 同上
$('p').before('<b>Hello!</b>'); // <b>Hello!</b><p>World!</p>
$('<b>Hello!</b>').insertBefore('p'); // 同上
原生近年新增的 insertAdjacentHTML() 與 before()/after()/append() 方法,寫起來已和 jQuery 幾乎無異。
reference = node.cloneNode(deep) // deep 為 true 時連子節點一起複製
clone() // jQuery:不複製事件
clone(true) // jQuery:連綁定的事件一起複製
element.removeChild(node) // 原生:移除指定子節點
$('ul li').remove() // jQuery:移除所有符合條件的元素
$('ul li').remove("[title!='Hello']");
$('ul').empty() // jQuery:清空節點內容
wrap() // 逐一單獨包裹
wrapAll() // 全部用同一個元素包起來
wrapInner() // 只包裹內部子內容
$('p').attr('title'); // 讀取
$('p').attr('title', 'My title'); // 設定單一屬性
$('p').attr({ title:'My title', class:'myClass' }); // 多屬性
原生的寫法直接多了:element.getAttribute('title') 與 element.setAttribute('title', 'My title')。
element.replaceChild(newChild, oldChild) // 原生
$('p').replaceWith('<h2>Hi</h2>'); // jQuery
$('<h2>Hi</h2>').replaceAll('p'); // jQuery,方向相反
element.style.fontSize = '14px'; // 原生,注意要用駝峰式
$(selector).css('font-size', '14px'); // jQuery,接受原本的 CSS 寫法
兩者最大的落差在這裡:原生 style 只能讀到行內樣式,拿不到外部樣式表設定的值;要讀最終樣式得用 getComputedStyle()。jQuery 的 .css() 幫你處理了這層差異。另外 jQuery 的 height()/width() 回傳不帶單位的數字,css('height') 則帶單位,計算時別搞混。
如果你的專案只需要幾個簡單特效、對象是現代瀏覽器,那麼上面絕大多數操作都能用原生 API 完成,省下載入成本很划算。反之,若動不動就要複雜選擇器、DOM 遍歷鏈、跨瀏覽器相容,jQuery 的開發效率優勢仍然明顯。判斷依據不是「哪個比較先進」,而是「這個專案省下來的時間值不值那 80KB」。