有個需求聽起來簡單,做起來卻棘手:選出頁面上所有「有背景圖片」的元素。這類條件無法用正規的選擇器表達式描述,因為它牽涉到每個元素的 computed style。
jQuery 的 DOM 過濾方法 filter() 允許傳入兩種參數:一個字串(也就是選擇器表達式),或一個函式。傳函式時,這個函式會對目前選擇集中的每個元素執行一次,返回值決定該元素去留——回傳假值就從集合中剔除,回傳真值則保留。
jQuery('*').filter(function(){
return !!jQuery(this).css('background');
});
這段程式碼選出所有具有背景圖片的元素。初始集合是全部元素(*),接著以函式為參數呼叫 filter(),逐一判斷有沒有 background 屬性,有就留、沒有就刪。
!! 是把任意值轉為布林值的簡寫。JavaScript 中的 undefined、空字串、null 與 false 都是假值,取兩次 NOT 之後就得到乾淨的 true/false。
嚴格說來 !! 並非必要,因為 jQuery 會自動把返回值轉型為 Boolean。但保留它是個好習慣:任何讀你程式碼的人都能立刻確定你的意圖,可讀性因此提升。
傳給 filter() 的函式中,可以用 this 引用目前元素。把它包進 jQuery 函式,就得到一個 jQuery 物件:
this // 常規的元素物件 jQuery(this) // jQuery 物件
// 篩出寬度介於 100 到 200 之間的元素
jQuery('div').filter(function(){
var width = jQuery(this).width();
return width > 100 && width < 200;
});
// 篩出子元素剛好是 10 個或 20 個的元素
jQuery('*').filter(function(){
var children = jQuery(this).children().length;
return children === 10 || children === 20;
});
<html>
<head>
<title></title>
<style type="text/css">
.c1{ background-color: yellow; }
.c2{ background-color: green; }
p{ background-color: pink; }
h3{ background-color: gray; }
</style>
</head>
<body>
<div class="c1">Bye Bye Beautiful</div>
<div class="c2">Nothing but the girl</div>
<p>The Lazy song</p>
<h2>If I die young</h2>
<h3>New soul</h3>
<script type="text/javascript" src="jquery.2.0.3.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
var ret = $('*').filter(function(index) {
return !$(this).css('background-color');
});
$.each(ret, function(index, val) {
$(val).css('background-color','black');
});
});
</script>
</body>
</html>
掌握 filter() 之後,凡是「無法用選擇器描述」的條件都能交給函式判斷,這在處理 computed style、位置尺寸或巢狀結構時特別好用。