按条件跳过每个函数中的元素

时间:2013-10-02 14:53:12

标签: jquery

如何在下一个条件下跳过jquery的each函数中的一些元素:

var number_of_td = 0;
$('td').each(function() {
    if (number_of_td == 0) {
       if ($(this).attr('id') == "1") {
           //skip the next three elements:
           //something like: $(this) = $(this).next().next().next();
        }
    }
    else if (number_of_td == 1) {
        if ($(this).attr('id') == "2") {
           //skip the next two elements
        }
    }
    else if (number_of_td == 2) {
        if ($(this).attr('id') == "3") {
           //skip the next element
        }
    }
    else if (number_of_td == 3) {
        if ($(this).attr('id') == "4") {
           //skip the next element
        }
    }
    else {
        number_of_td++;
        if (number_of_td == 4) {
             number_of_td = 0;
        }
    }
});

例如:

<td attr="1"></td>
<td attr="6"></td>
<td attr="7"></td>
<td attr="9"></td>
//-------------------
<td attr="2"></td>
<td attr="5"></td>
<td attr="3"></td>
<td attr="6"></td>
//-------------------
<td attr="7"></td>
<td attr="2"></td>
<td attr="8"></td>
<td attr="6"></td>

如果存在第四个条件之一,则跳至带有attr=2的td元素。

在这个例子中,第一个td属性是1,所以它跳过attr = 2而不检查其他元素(attr = 6,7,9)。

2不等于1,5不等于2,3等于3,所以跳过attr = 7等等。

我希望你能理解我的榜样。

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:2)

添加计数器变量,如果计数器未达到零,则跳过循环:

$('td').each(function() {
    if (+$(this).data('counter')>0) { 
        $(this).data('counter', $(this).data('counter')-1); // decrement counter
        return; // continue to next loop iteration
    }
    if (number_of_td == 0) {
       if ($(this).attr('id') == "1") {
           $(this).data('counter', 2); // skip two more after this one
           return; // skip to next loop iteration
        }
    }