2011-12-28 175 views
2

所以我想要做的是獲取HTML表的最後一行。如果這行有一個特定的類,我會忽略這一行並選擇前一行。然後這將從桌子的末端開始循環,直到找到沒有這個班級的行。使用Javascript循環遍歷錶行/ Jquery

我想它可能涉及for循環,檢查行類,然後JQuery的row.prev方法,但仍然不太確定如何處理這個。

在此先感謝!

+0

什麼是在服務器端生成HTML表? – 2011-12-28 15:34:54

+0

使用jQuery,它是一個單線程,如下所示。如果沒有jQuery,它仍然只有大約三或四行使用for循環遍歷['table.rows'集合](https://developer.mozilla.org/en/DOM/table.rows),檢查類並爆發找到循環。 – nnnnnn 2011-12-28 15:45:09

回答

1

假設你有下面的HTML:

<table id="mytable"> 
    <tbody> 
     <tr> 
      <td>1</td> 
     </tr> 
     <tr id="YouFoundMe"> 
      <td>1</td> 
     </tr> 
     <tr class="certainclass"> 
      <td>1</td> 
     </tr> 
     <tr class="certainclass"> 
      <td>1</td> 
     </tr> 
     <tr class="certainclass"> 
      <td>1</td> 
     </tr> 

    </tbody> 
</table> 

你可以這樣做:

var elWithoutClass = $('#mytable tr:not(.certainclass):last'); 

if (elWithoutClass.length) { 
    alert(elWithoutClass.get(0).id); 
    // alerts "YouFoundMe" 
} 
  • :not(.certainclass)將消除<tr>無類 'certainclass'
  • :last將讓你的最後一個

我邀請你去車請訪問jquery的Selectors documentation page瞭解更多關於它們的信息。

3

爲了獲得不具有某一類的最後錶行,說targetClass,你可以這樣做:

$("tr:not(.targetClass):last"); 

我不知道你想和這個錶行做什麼,但如果你要添加targetClass到最後一行沒有它,它看起來像這樣

$("tr:not(.targetClass):last").addClass("targetClass"); 

看看這個fiddle看到它在行動

2

這個例子說明了如何獲得最後的每個表的當前頁面上:http://jsfiddle.net/JBnzK/

$('table').find('tr:last').each(function(){ 
    if ($(this).hasClass('stupid')) { 
     $(this).css('color', 'red'); 
    } else { 
     $(this).css('color', 'green'); 
    } 
});