鏈式操作是 jQuery 最具特色的寫法之一,能把多個操作串成一條、既簡潔又高效。但如果用不當,反而會失去它的優勢。本文比較「糟糕」與「建議」兩種寫法。
每次都重新對同一元素操作,讓 jQuery 重複查找、反覆呼叫:
$second.html(value);
$second.on('click', function(){
alert('hello everybody');
});
$second.fadeIn('slow');
$second.animate({height:'120px'}, 500);
用鏈式串接,一次到底:
$second.html(value);
$second.on('click', function(){
alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'}, 500);
差別在於:鏈式寫法只查找一次元素,後續方法直接在回傳的 jQuery 物件上接續執行,程式碼更短、可讀性更高,也能減少不必要的開銷。大多數 jQuery 方法都會回傳物件本身(或集合),正是為了支援這種串接風格。