2016-05-17 43 views
1

我有一個動態生成的HTML代碼,它看起來像:遍歷匹配表上的一個按鈕,當點擊

<div class="systeme"> 
    <table method="post" class="table table_cultures"> 
     <tr class="formRows"> 
      <td>Something</td> 
      <td>Something</td> 
      <td>Something</td> 
      <td>Something</td> 
     </tr> 
    </table> 
    <button class="btn btn-default valider_systeme_culture">Valider</button> 
</div> 

<div class="systeme"> 
    <table method="post" class="table table_cultures"> 
     <tr class="formRows"> 
      <td>Something 2</td> 
      <td>Something 2</td> 
      <td>Something 2</td> 
      <td>Something 2</td> 
     </tr> 
    </table> 
    <button class="btn btn-default valider_systeme_culture">Valider</button> 
</div> 

當我點擊一個按鈕,我想循環使用JavaScript通過匹配表只有這張桌子。

目前,當我點擊一個按鈕,我得到這兩個表的所有數據。

在Javascript中,我有這樣的:

var table = $(".table_cultures tbody"); 
table.find('.formRows').each(function (i) { ... }); 

我也試圖與功能.parents()但在那之後,我不能做一個.find('.table_cultures tbody),這是行不通的。問題是我需要找到table_cultures tbody,因爲它允許我在存在tbody時遍歷行。

我該怎麼做才能通過正確的表循環?

回答

0

您可以使用$(this).prev('table')其中$(this)點擊按鈕,然後你會得到prev("table")DEMO

$('.btn').click(function() { 
    $(this).prev('table').find('.formRows').css('background', 'red') 
}) 
+0

謝謝,但只有在按鈕和表格之間沒有任何東西的時候它才能工作。就我而言,我有兩個元素。我知道在我的例子中沒有任何東西,但它是我的代碼的簡化版本:/我通過添加一個div來編輯小提琴,只是爲了讓您看到:https://jsfiddle.net/Lg0wyt9u/852/ – Erlaunis

+0

對於第二個示例找到你的代碼應該看起來像這樣https://jsfiddle.net/Lg0wyt9u/854/ –

+0

它在小提琴中工作,但它不會當我嘗試重現真實 – Erlaunis

0

Nenad Vracar的做法幾乎是好,但原來的問題明確指出,表是動態生成的,所以委託事件應該更安全。

$('body').on('click', '.btn', function() { 
    $(this).siblings('table') 
    .find('.formRows') 
    .each(function (index, elem) { 
     //var $elem = (this); 
     //either use the function parameters is the this variable 
     //to do something with the current row 
    }); 
}); 
+0

函數'prev'不能與我一起工作,因爲我有按鈕和表。如果你只有一個表,那麼請修改'prev'函數爲'兄弟';如果你只有一個表,請參閱 – Erlaunis

+0

的評論。否則使用更嚴格的選擇器 – zedling