2013-10-02 67 views
0

跳過在每個功能元件如何可以由下一個條件跳過的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,等等

我希望你能理解我的例子。

任何幫助讚賞!

+0

.filter(...)http://api.jquery.com/filter/ – Oliboy50

+0

您的jQuery正在尋找一個id('$(this).attr('id')'),但你的td元素沒有id。另外,你爲什麼使用'each'功能? – andi

+0

使用return false; – Guerra

回答

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 
     } 
    } 
+0

請注意:如果你看OP的代碼,'.attr('id')'應該是'.attr('attr')'。我不認爲他使用的是id:s,因爲有多個相同值的出現。 – Johan

+0

@Johan我認爲有理由認爲他的JavaScript是準確的,但他的HTML是一個簡化的(錯誤的)表示。 – Blazemonger