jQuery appendToを使ってテーブルを作成するサンプル
環境
Windows 10 home 64bit
Google Chrome 107.0.5304.122
書式
1.$(“要素2").appendTo(要素1);
appendToを使って指定子要素の最後に移動します。
2.$(“セレクター名").append(要素)
appendを使って指定の要素の子要素の最後に追加します。
3.ボタンのイベントの定義
$(“#ボタンのID名").click(function(){処理コード})
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btnchk").click(function(){
const tableA = $("<table><tbody>");
for(let i=0; i<2;i++){
// 子要素の最後に移動する
$("<tr><td>東京</td><td>大阪</td></tr>").appendTo(tableA);
}
//指定の要素の子要素の最後に追加
$("</tbody></table>").appendTo(tableA);
//divに追加
$("#show").append(tableA);
});
});
</script>
<style>
table {
border-collapse: collapse;
width: 40%;
}
table td {
border: 1px solid;
}
</style>
</head>
<body>
<div id="show"></div>
<button id="btnchk">追加</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btnchk").click(function(){
const tableA = $("<table><tbody>");
for(let i=0; i<2;i++){
// 子要素の最後に移動する
$("<tr><td>東京</td><td>大阪</td></tr>").appendTo(tableA);
}
//指定の要素の子要素の最後に追加
$("</tbody></table>").appendTo(tableA);
//divに追加
$("#show").append(tableA);
});
});
</script>
<style>
table {
border-collapse: collapse;
width: 40%;
}
table td {
border: 1px solid;
}
</style>
</head>
<body>
<div id="show"></div>
<button id="btnchk">追加</button>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btnchk").click(function(){ const tableA = $("<table><tbody>"); for(let i=0; i<2;i++){ // 子要素の最後に移動する $("<tr><td>東京</td><td>大阪</td></tr>").appendTo(tableA); } //指定の要素の子要素の最後に追加 $("</tbody></table>").appendTo(tableA); //divに追加 $("#show").append(tableA); }); }); </script> <style> table { border-collapse: collapse; width: 40%; } table td { border: 1px solid; } </style> </head> <body> <div id="show"></div> <button id="btnchk">追加</button> </body> </html>
実行結果
ボタン「追加」を押すと、2行2列のテーブルを作成します。