ajaxで追加した要素にイベント

ajaxで追加した要素は、js読み込みの時点では存在していないので、後から追加する要素にイベント(クリックなど)を設定することができない。
#table_areaの中身をajaxで追加するとして、そのテーブルの中のtdにイベントを設定したい場合。

これでは動かない。tdがないから。
$(“td”).on(‘click’, function() {

こうする
$(“#table_area”).on(‘click’,’td’, function() {

#table_areaは最初から存在するものとする。
onの関数の二つ目の引数に、トリガーとなる要素を設定するのです。

複数のトリガーがある場合はこんな感じ。
$(“#table_area”).on({
‘mouseenter’: function() {
if(!$(‘#toggleCancelBtn’).prop(‘checked’)){
if ($(this).text() === “” && !$(this).hasClass(‘rsvFlag’)) {
$(this).addClass(‘hoverFlag’);
}
}else{
if ($(this).hasClass(‘myReserve’)) {
$(this).addClass(‘hoverFlag’);
}
}
},
‘mouseleave’: function() {
if(!$(‘#toggleCancelBtn’).prop(‘checked’)){
if ($(this).text() === “” && !$(this).hasClass(‘rsvFlag’)) {
$(this).removeClass(‘hoverFlag’);
}
}else{
if ($(this).hasClass(‘myReserve’)) {
$(this).removeClass(‘hoverFlag’);
}
}
},
},”td”);

前の記事

array_filter

次の記事

配列を作るなど