问题描述
我试图将click事件添加到index.handlebars文件中的删除按钮。但是,即使我在javascript文件中定位了该按钮,该按钮也没有注册点击。 这是下面的车把代码:
<ul class="collection with-header">
{{#each Jokes}}
<li class="collection-item">
<div>Jokes: {{joke}} {{username}}
<button type="submit" data-id="{{id}}" class="waves-effect waves-light btn userdelete" method="delete">delete the joke</button>
</div>
</li>
{{/each}}
<h4></h4>
</ul>
这是javascript文件中的click事件:
$(".userdelete").on("click",function () {
const idToDelete = $(this).data("id");
console.log("click");
$.ajax({
url: `/api/Jokes/${idToDelete}`,method: "DELETE"
}).then(function () {
location.reload();
});
});
我在做什么错? console.log的“ click”甚至没有出现在浏览器控制台中。非常感谢您的帮助。
解决方法
这是由于.userdelete元素是动态生成的-该元素尚不存在,因此您无法将任何内容绑定到该元素。尝试将其绑定到这样的父元素:
$(".collection").on("click",".userdelete",function() { /* ... */ });
有关更多信息,请查看此post