2016-10-26 9 views
0

私は、クリックされたボタンの隣にあるテーブルを探しています。 すべてのテーブルとボタンが動的に作成されます。次のテーブルを見つける方法tbody jquery

<button type="button" onclick="addRows(this)">Add Row</button> 
<table> 
    <tbody> 
     <td>A</td> 
     <td>A</td> 
    </tbody> 
</table> 
<button type="button" onclick="addRows(this)">Add Row</button> 
<table> 
    <tbody> 
     <td>B</td> 
     <td>B</td> 
    </tbody> 
</table> 
<button type="button" onclick="addRows(this)">Add Row</button> 
<table> 
    <tbody> 
     <td>C</td> 
     <td>C</td> 
    </tbody> 
</table> 
<button type="button" onclick="addRows(this)">Add Row</button> 
<table> 
    <tbody> 
     <td>A</td> 
     <td>A</td> 
    </tbody> 
</table> 

私はこれを使用していますが、私はボタンの隣のテーブルを取得することができます:

$(this).closest("table").find("tbody"); 
+0

'onclick =" addRows(this) "のようなインラインイベントハンドラを避ける" – j08691

+0

はい、次はこのために使うことができます。 – Geeky

答えて

1

あなたは次の要素を取得するために.next()を使用する必要があります。

$(this).next("table").find("tbody") 

.closest()要素ではなく、隣接する素子を含む最も近いを見つけるためのものです。ボタンがテーブルの中にないので、$(this).closest("table")は何も一致しません。

男の子jQueryデザイナーは、この名前を付けたときに戸惑いました。それは初心者の間で混乱の最も一般的な原因と思われる。

関連する問題