LoginSignup
3
3

More than 5 years have passed since last update.

jQueryで動的に生成したtableにイベントリスナーをつける

Posted at

jQueryで動的に生成したテーブルにイベントリスナーを付けようと
例を色々探してみましたが、いい塩梅の例が見付からなかったため自分用に書いておきます。

HTML

html
<body>
<table id="table"></table><!--ここに行を追加-->
</body>

jQuery

js
$('#table').on('click','#name', function(){
  sample();//呼び出す関数
});
...
...
function setth(){
  var row = document.createElement("tr");//trを生成
  var th = document.createElement("th");//thを生成
  th.id="name";//thにidを付与
  th.innerHTML="名前";
  row.appendChild(th);//行にthを追加
  $("#table").append(row);//rowをテーブルへ追加
}

これにより生成されるhtmlはこうなります。

html
<body>
<table id="table">
  <tr>
    <th id="name">name</th>
  </tr>
</table>
</body>
名前
hoge
fuga
poyo

テーブルの名前のセルを押すとクリックイベントが起こせます。
(tdは各自で増やしてください。)

詳しい説明は以下を参考に...
参考にしたサイト
onメソッドを利用したイベントの設定-jQuery入門講座

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3