javascript - Javascript - 将点击监听器添加到加载的 html
问题描述
我有一个以前的问题 reloading html via ajax:
javascript - 从 ajax 调用加载 html 内容
但我在附加点击监听器时遇到了小问题:
<html th:remove="tag" xmlns:th="http://www.thymeleaf.org" xmlns:ber="http://berwickinsurance.com/thymeleaf"
xmlns:eph="http://ephibian.com/thymeleaf" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<div>
<div id="note-list-container2">
....
</div>
<div id="file-list-container2">
<table style="width: 100%; height: 100%" class="table">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Category</th>
<th>Created On</th>
<th>Size</th>
<th></th>
</tr>
</thead>
<tbody>
<th:block th:each="note : ${model.notes}" th:object="${note}">
<tr th:each="file : *{files.data}" th:object="${file}">
<td><i
th:replace="~{layout/custom-frag::file-ico(*{mimeType})}"></i></td>
<td><a target="file"
th:href="@{*{#uris.escapePath('/files/'+id+'/'+name)}}"><strong
th:text="*{name}">contractUHCSigned.pdf</strong></a></td>
<td><span class="badge" th:text="${note.category.name}">Category</span>
</td>
<td> <span th:text="*{#joda.defaultDateTime(createDate)}">Create On</span></td>
<td><th:block
th:text="*{#prettyTime.humanReadableByteCount(size, true)}">400 kb</th:block>
</td>
<td><a target="file"
th:href="@{*{#uris.escapePath('/files/'+id+'/'+name)}}">View</a></td>
<td ><a id="noteFileDeletion" onClick="handleFiledeletion()" title="Remove File" class="delete-btn text-danger" data-confirm="delete file"><i class="fa fa-remove"></i></a></td>
</tr>
</th:block>
</tbody>
</table>
</div>
</div>
<script>
function handleFiledeletion(){
.....
}
</script>
</html>
它不会触发该handleFiledeletion
方法。
我尝试了另一种方法:
$("#noteFileDeletion").on('click', function() {
var deleteBtn = $(this);
var url = $(this).data('url');
url = url +"?csrf_token="+App.config.csrfToken;
var msg = "Are you sure you want to "+$(this).data('confirm')+"?";
bootbox.confirm(msg, function(result){
if(result){
$.ajax({
processData : false,
"type" : "DELETE",
"url" : url,
})
.success(function( data ) {
window.location.href='/applicationProducts';
});
}
});
});
但它也没有触发事件处理程序。
我错过了什么?
解决方案
使用 时.on()
,您必须确保将.on()
侦听器附加到初始页面加载时已在 DOM 中的元素。
试试这个 - 如果它有效,那么您可以尝试将侦听器移到树的下方:
$(document).on('click', function(){
var deleteBtn = $(this).find('#noteFileDeletion');
etc.
更新:
我已经用缺失的部分更新了上面的代码——非常感谢@David 发现了这个遗漏。
$(document).on('click', '#noteFileDeletion', function(){
alert('You clicked ID noteFileDeletion');
});
推荐阅读
- c++ - 是否可以部署一个通过并覆盖键盘击键的 C 代码?
- mysql - 如何处理Mysql中的空主键?
- python - 由于在执行主循环之前无法填充变量,在 tkinter GUI 中请求模块 MissingSchema 错误:如何解决这个问题?
- c# - 使用对象字段作为函数参数其他字段
- c++ - 如何执行模板化结构的添加?
- vue.js - 如何实现多个*独立*行(vuetify)伪轮播?
- python - 如何使用 Selenium 从 https://temp-mail.org 提取临时电子邮件地址
- javascript - 如何将 onclick 函数添加到自定义 React 组件?
- javascript - 如果 Google Analytics 在源代码中显示 UA-3XXXXX-1 ID 怎么办
- javascript - Chrome 扩展程序仅在新标签中正常运行