2016-07-14 30 views
0

をクリックしたときに、私はこのようになりますいくつかの列、とtable持つ要素の兄弟に属性を追加します。私は何をしたいか子要素が

<tr role="row" class="odd"> 
    <td class="sorting_1"> 
     <button id="1" class="btn btn-info btn-sm _edit_btn">Edit</button> 
    </td> 
    <td>1</td> 
    <td>Asht</td> 
    <td>5</td> 
    <td>16</td> 
    <td>5</td> 
    <td>3</td> 
    <td>3</td> 
    <td>2</td> 
    <td>Sughd</td> 
    <td>2</td> 
    <td>3505207000000</td> 
    <td>3</td> 
    <td>2</td> 
    <td>15</td> 
    <td>5</td> 
</tr> 

、各<td>に属性を追加することです要素は、テーブルの最初の<td>にあるボタンをクリックしてクリックします。

私はこの目的のためにjQueryを使用しています。 <td>要素は<button>要素の兄弟ではなく、他の<td>要素の兄弟ではないため、兄弟関数を使用して処理しようとしましたが、機能しません。

+0

「* '​​'要素は '

+0

最初のものではないすべてのtdに属性を追加しますか? – Roysh

答えて

2

はこれを行うには、その後、find()tdを取得します、次のように:あなたはあなたが言及したようsiblings()を使用することを好む場合

$('button').click(function() { 
    $(this).closest('tr').find('td').attr('foo', 'bar'); 
}); 

は、その後、あなたは親を得ることができますその上と使用siblings():それはあなたの意図した場合は、このバージョンでは、最初のtd要素に属性を追加しないこと

$('button').click(function() { 
    $(this).closest('td').siblings().attr('foo', 'bar'); 
}); 

注意。

1

あなたはそれでtd.closest()方法を使用して、最も近いtr要素に横断し、その後、見つけることができます:あなたはbuttonの親trを見つけるためにclosest()を使用することができます

$('button').click(function(){ 
    $(this).closest('tr').find('td').attr('someattr','attrval'); 
}); 
1

次の2つのケースについて、このいずれかを使用できます。

$("button").click(function(e) { 
    //if you want to add attribute to all tds then use this line 
    $(this).closest("tr").find("td").attr("your-attribute", "value"); 

    //if you want to add attribute to all tds except the first one then use this line 
    $(this).closest("tr").find("td:not(.sorting_1)").attr("your-attribute", "value"); 
});