重複呼叫 $('#id') 會導致瀏覽器反覆遍歷 DOM 樹,影響效能。本文示範如何將選擇器快取至模組物件,結合事件代理、模組化模式,實現高效能、可維護的 jQuery 代碼組織。
$(document).ready(function() {
$('#some-selector').on('hover', function() {
$(this).fadeOut('slow').delay(400).fadeIn();
console.log($(this).text());
});
$('#another-element').on('hover', function() {
$(this).slideUp();
});
$('#some-selector').on('click', function() { // 再次查詢 #some-selector
alert('You have clicked a featured element');
});
$('#another-element').on('mouseout', function() { // 再次查詢
$(this).slideUp();
});
});
// 1. 定義選擇器映射表(集中維護、易重構)
const Selectors = {
featured: '#some-selector',
panel: '#another-element',
modal: '.modal-overlay',
// 複雜選擇器可用函數動態生成
getRow: (id) => `#dataTable tr[data-id="${id}"]`
};
// 2. 快取 jQuery 物件(DOM Ready 後一次性查詢)
let $cache = {};
function initCache() {
$cache = {
$featured: $(Selectors.featured),
$panel: $(Selectors.panel),
$modal: $(Selectors.modal)
};
}
// 3. 使用快取物件
$(document).ready(function() {
initCache();
$cache.$featured.on('hover', function() {
$(this).fadeOut('slow').delay(400).fadeIn();
console.log($(this).text());
});
$cache.$panel.on('hover', function() {
$(this).slideUp();
});
$cache.$featured.on('click', function() {
alert('You have clicked a featured element');
});
$cache.$panel.on('mouseout', function() {
$(this).slideUp();
});
});
const FeaturedComponent = (function() {
let $el, $panel;
function cacheElements() {
$el = $('#some-selector');
$panel = $('#another-element');
}
function bindEvents() {
$el.on('hover', onHover).on('click', onClick);
$panel.on('hover mouseout', onPanelHover);
}
function onHover() {
$(this).fadeOut('slow').delay(400).fadeIn();
console.log($(this).text());
}
function onClick() {
alert('Featured clicked');
}
function onPanelHover(e) {
$(this)[e.type === 'mouseout' ? 'slideUp' : 'slideDown']();
}
return {
init: function() {
cacheElements();
bindEvents();
},
refresh: function() { // 針對動態新增元素重新快取
cacheElements();
bindEvents();
}
};
})();
$(document).ready(() => FeaturedComponent.init());
// 容器不變,子元素動態新增/移除
$('#container').on('click', '.dynamic-item', function() {
// this 為觸發事件的 .dynamic-item
console.log($(this).data('id'));
});
// 無需重新快取 .dynamic-item,效能最優
$('#id') | ~15ms | 反覆遍歷 DOM |
| 變數快取 const $el = $('#id') | ~0.2ms | 單次查詢,直接引用 |
| 事件代理 | ~0.1ms | 無需快取子元素,容器固定 |
initCache()。$cache = {} 或用 WeakMap。Selectors 物件修改,全局生效。$cache.$list.filter('.active') 仍會遍歷,不如重新查詢 $('.active', $container)。選擇器快取是 jQuery 專案效能優化的第一步,配合模組化封裝與事件代理,能構建清晰、高效、可維護的前端代碼庫。