jQuery 的核心設計哲學之一就是「鏈式調用」。簡單來說,大多數 jQuery 方法會回傳 jQuery 物件本身(this),讓我們可以像串珠子一樣,將多個操作寫在同一行,程式碼更簡潔、可讀性更高,甚至能帶來微小的效能提升。
// ❌ 糟糕寫法:每行都重新查詢 DOM
$second.html(value);
$second.on('click', function(){ alert('hello everybody'); });
$second.fadeIn('slow');
$second.animate({height:'120px'}, 500);
這樣寫會讓瀏覽器執行 4 次 DOM 查詢($second),不僅冗長,效能也較差。
// ✅ 建議寫法:單次查詢,鏈式操作
$second
.html(value)
.on('click', function(){ alert('hello everybody'); })
.fadeIn('slow')
.animate({height:'120px'}, 500);
優點一目了然:
$second 只執行一次選取當鏈條較長時,建議每個方法換行並縮排:
$('#myElement')
.addClass('active')
.css({ opacity: 0.5, color: '#333' })
.slideDown(300)
.queue(function(next) {
console.log('動畫完成');
next();
});
.width()、.val() 取值時回傳數值而非 jQuery 物件).end() 回到上一個選取集合.each(function(){ console.log(this); }) 檢查元素狀態養成鏈式操作習慣,是寫出專業級 jQuery 代碼的基礎。下次動手前,先問自己:「這裡能不能串起來?」