我附加的html元素的事件监听器不起作用。该按钮的作用是它将打开一个弹出窗口,提示用户进行删除确认。
我正在以这种方式创建视图页面,而不是常规的html和jsp代码方式,因为我想使用ajax和jquery进行分页。那时事件监听器可以正常工作。我省略了代码,因为它不太相关。
我在做什么错了?
viewAnnouncements.jsp
<table>
<thead>
<!--Sets the table headings-->
</thead>
<script type="text/javascript">
$('document').ready(function() {
$.get("processPagination.jsp?requestType=getRecords, function(data) {
var JSONData = JSON.parse(data);
for(i=0; i<recordsToFetch; i++){
const record = JSONData.results[i].split(",");
const title = record[0];
$("tbody").append("
<tr>
<td><a>"+title+"</a></td>
<td>
<p data-placement='top' data-toggle='tooltip' title='Delete'>
<button class='btn btn-danger btn-xs announcement-delete-button' data-title='Delete' data-id='"+index+"'>
<i class='far fa-trash-alt' ></i></button></p>
</td>
</tr>");
}
});
</script>
<tbody>
<!--Rows are appended here-->
</tbody>
main.js
$('document').ready(function() {
$('.announcement-delete-button').on('click', function() {
const id = $(this).data().id;
$('.grey-screen').show();
$('#announcement-delete').fadeIn();
$('.announcement-delete-yes')
.attr("onclick",
"window.location.href='/testweb/announcementController?Submit=delete
);
});
});
编辑:我已经尝试将事件侦听器绑定到tbody并调用子选择器“ announcement-delete-button”,但它仍然不起作用。
答案 0 :(得分:0)
您需要将事件侦听器绑定到主体,而不是直接类
$('body').on('click', '.announcement-delete-button', function (e) { /*Your code here*/ });
答案 1 :(得分:0)
在这种情况下,您只需要限制字符串并在添加时将它们添加在一起
$("tbody").append("" +
"<tr>" +
" <td><a>"+title+"</a></td>" +
" <td>" +
" <p data-placement='top' data-toggle='tooltip' title='Delete'>" +
" <button class='btn btn-danger btn-xs announcement-delete-button' data-title='Delete' data-toggle='modal' data-target='#delete' data-id='"+index+"'>" +
" <i class='far fa-trash-alt' ></i></button></p>" +
" </td>" +
"</tr>");