jQuery 本質上是 JavaScript 的封裝與擴充,目標是「用更少的程式碼完成更多事」。釐清兩者的對應關係,一方面有助於理解 jQuery 背後做了什麼,另一方面在不需要它的場合也能寫得更精簡。以下按常見操作分類對照。
原生寫法:
function first(){ alert('first'); }
function second(){ alert('second'); }
window.onload = first;
window.onload = second;
// 只會執行第二個,後者覆蓋前者
要改進就得手動合併:
window.onload = function(){
first();
second();
};
jQuery 則可以寫多段、全部執行:
$(document).ready(function(){ first(); });
$(document).ready(function(){ second(); });
// 兩段都會執行
document.getElementById('idName') // 原生取 ID
$('#idName') // jQuery 取 ID
// 原生沒有預設的 class 查詢方法
$('.className') // jQuery 取 class
document.getElementsByTagName('tagName') // 原生取標籤
$('tagName') // jQuery 取標籤
var para = document.createElement('p');
document.body.appendChild(para); // 作為 body 的最後一個子節點
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'); // 同上
// 原生
parentElement.insertBefore(newElement, targetElement);
var imgs = document.getElementById('imgs');
var para = document.getElementsByTagName('p');
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'); // 同上
reference = node.cloneNode(deep); // deep 為 true 時連子節點一起複製 clone() // 只複製元素,不含事件 clone(true) // 連綁定的事件一起複製
reference = element.removeChild(node); // 原生 remove(); // 從 DOM 中刪除所有符合條件的元素 empty(); // 清空節點內容,但保留節點本身
remove 可搭配過濾條件,寫起來相當靈活。
wrap() // 逐一包裹 wrapAll() // 全部包進同一個元素 wrapInner() // 包裹內部內容
原生 JavaScript 沒有等價的簡便方法。
$('p').attr('title'); // 讀取
$('p').attr('title', 'My title'); // 設定單一屬性
$('p').attr({ 'title': 'My title', 'class': 'myClass' }); // 一次設定多個
reference = element.replaceChild(newChild, oldChild); // 原生
$('p').replaceWith('<h2>Hi</h2>');
$('<h2>Hi</h2>').replaceAll('p');
原生用 element.style.property,只能取得行內樣式,讀不到外部樣式表設定的值;且 CSS 屬性中的 font-size 要寫成駝峰式的 fontSize。
jQuery 的 .css() 可以讀取運算後的樣式:
$(selector).css('font-size');
此外 jQuery 另外提供 height() 與 width(),回傳不含單位的數值;而 css('height') 回傳的是帶單位的字串。這差異在做計算時很容易造成 bug,值得記住。
jQuery 最大的成本是那份檔案本身與一層函式呼叫。在只需要 getElementById、addEventListener 這類基本操作的場合,原生寫法效能更好、依賴更少。合理的策略是:DOM 操作密集、需要大量遍歷與篩選時用 jQuery;單純的元素取得與事件綁定則直接用原生 API。