2016-11-26 5 views
0

私は、特定の表のセルの#idをjQueryを使用して変数に取り込もうとしていますが、大したことはありません。誰も助言を提供できますか?私はフィドルを作ったherejQueryを使用して特定の表のセルをターゲットに設定するにはどうすればよいですか?

HTML

<input type="button" id="button" value="Click Me" /> 

<table id="myTable1"> 
    <tbody> 
    <tr> 
     <td id="1"> 
     cell 1 
     </td> 
     <td id="2"> 
     Get the id of this cell 
     </td> 
     <td id="3"> 
     cell 2 
     </td> 
    </tr> 
    </tbody> 
</table> 

jQueryの

$(document).ready(function() { 
    $("#button").click(function() { 
    var td = $(this).closest('table').attr('id'); //find table id 
    alert(td); 
    }); 
}); 
+0

どのようにコードが** **あなたがターゲットとしたいセルを知っている必要がありますか? –

+0

私はそれで私を助けてくれることを願っています。 – JulianJ

+0

'$(this).next( 'table')のように' nearest'の代わりに 'next'を使います。attr( 'id');' – Azim

答えて

1

あなたは、各セルからすべてのIDを取得したい場合はここで最初のソリューションです。それが役に立てば幸い!

$(document).ready(function() { 
 
$("#button").click(function() { 
 
    var ids = []; 
 
    $("tr > td").each(function(index){ 
 
    ids.push($(this).attr("id")); 
 
    }); 
 
    alert(ids); 
 
}); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<input type="button" id="button" value="Click Me" /> 
 

 
<table id="myTable1"> 
 
    <tbody> 
 
    <tr> 
 
     <td id="1"> 
 
     cell 1 
 
     </td> 
 
     <td id="2"> 
 
     Get the id of this cell 
 
     </td> 
 
     <td id="3"> 
 
     cell 2 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table>

は、ここであなたが見たい場合は第二の溶液のIDの一つずつ。

$(document).ready(function() { 
 
$("#button").click(function() { 
 
    $("tr > td").each(function(index){ 
 
    alert($(this).attr("id")); 
 
    }); 
 
}); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<input type="button" id="button" value="Click Me" /> 
 

 
<table id="myTable1"> 
 
    <tbody> 
 
    <tr> 
 
     <td id="1"> 
 
     cell 1 
 
     </td> 
 
     <td id="2"> 
 
     Get the id of this cell 
 
     </td> 
 
     <td id="3"> 
 
     cell 2 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table>

関連する問題