在jQuery中,使用.each()
方法可以實現(xiàn)對集合中的每個元素進行遍歷。如果你想要根據(jù)特定條件進行遍歷,可以在回調(diào)函數(shù)中添加條件判斷。以下是一個示例:
$(document).ready(function() {
// 假設(shè)我們有一個包含數(shù)字的列表
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// 使用.each()方法遍歷數(shù)字列表,并檢查每個數(shù)字是否偶數(shù)
numbers.each(function(index, value) {
// 使用條件判斷,只有當數(shù)字是偶數(shù)時才執(zhí)行回調(diào)函數(shù)內(nèi)的代碼
if (value % 2 === 0) {
console.log(value + " 是偶數(shù)");
}
});
});
在這個示例中,我們首先創(chuàng)建了一個包含數(shù)字的列表。然后,我們使用.each()
方法遍歷這個列表。在回調(diào)函數(shù)中,我們使用條件判斷value % 2 === 0
來檢查當前數(shù)字是否為偶數(shù)。如果條件滿足,我們就輸出相應(yīng)的信息。