[英]Jquery event not working after append html
我有 ajax 請求,當 ajax 成功時,我使用 ajax 響應中的 html 替換內容。
控制器是這樣的:
$html = view('payroll-cutoff.data-attendance-group', compact('payroll_group', 'payroll_cutoff_group'))->render();
return response()->json([
'success' => true,
'data' => $html,
]);
在 ajax 成功中,我有一些代碼來操作視圖。 但不知何故,在我成功替換tbody
的 html 內容后,jquery 事件不再起作用,即使當我檢查元素時,我成功地使用來自 ajax 響應的 html 替換了內容。
success:function(response){
// thisObj = '.process-attendance'
let element = response.data;
let el_data = $(element).filter('.group-payroll').find('.body-component').html();
thisObj.closest('table').find('tbody').html(el_data);
// code bellow not working
thisObj.closest('table').find('thead').addClass('done-group');
thisObj.closest('table').find('tbody').addClass('done-group');
},
例如,我在點擊功能上有這個,但在 ajax 成功后它不再工作了。
$(".show-emp").click(function () {
showEmployee($(this));
});
function showEmployee(el)
{
$(el).closest('tbody').find('.employee').toggle();
$(el).closest('tbody').find('.employee-head').toggle();
}
這是觀點:
<table class="table group-payroll">
<thead class="head-component">
<tr>
<th colspan="7"></th>
</tr>
</thead>
<tbody class="body-component">
<tr>
<td style="width: 100%" colspan="7">
<a href="javascript:void(0)" class="btn btn-sm mb-2 checkall process-attendance">Process Attendance</a>
<a href="javascript:void(0)" class="btn btn-sm mb-2 checkall me-5 show-emp"></a>5 Employee
</td>
</tr>
<tr class="employee-head" style="display: none">
<td>No</td>
<td>Name</td>
<td>HK</td>
<td>IN</td>
</tr>
<input type="hidden" class="process-done" value="">
<input type="hidden" name="employee_id[]" class="employee_id" value="">
<tr class="employee" style="display: none">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
讓我知道以下代碼是否有效
$(".group-payroll").on('click', '.show-emp', function () {
showEmployee($(this));
});
查看jquery 文檔。 有兩種類型的事件處理程序,直接的和委托的。 這是一個委托事件處理程序。
委托事件處理程序的優點是它們可以處理來自以后添加到文檔的后代元素的事件。
在您的情況下,成功后添加到表中的 HTML 是后代元素。
您需要嘗試如下代碼段。
有用的鏈接:
https://api.jquery.com/on/
https://api.jquery.com/click/
$(document).on("click", ".show-emp", function () {
showEmployee($(this));<br>
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.