附加html数据时不能多次单击按钮 [英] Can't click button more than one time when append html data
问题描述
jquery有问题.我使用ajax发送ID以从数据库中删除,然后返回html文件以更新内容而无需重新加载页面(我使用struts 2),第一次运行或重新加载页面时,我的按钮工作正常(行已删除并且我的内容已更新),但是当我尝试再次单击按钮,但没有响应.
I've a problem with jquery. I use ajax to send id to delete from DB and then return html file to update content without reload page (I use struts 2) , first time run or reload page my button work fine ( row was deleted and my content was updated) but when I try to click button again , it doesn't respond.
我的脚本
$(document).ready(function() {
$(".btnEdit").click(function() {
alert("Edit");
});
$(".btnDelete").click(function() {
id = $(this).attr('id');
alert("Delete ID : " + id);
$.ajax({
url: "delete",
type: 'POST',
data: {'id': id},
cache: false,
success: function(data, textStatus, jqXHR) {
$('.catagoryContent').remove();
$('.container').append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("error");
}
});
});
});
对不起,我忘了返回数据代码.
Sorry, I forgot return data code.
<div class="catagoryContent">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Edit / Delete</th>
</tr>
</thead>
<tbody>
<s:iterator value="catagoryList" var="catagory">
<tr>
<td>${catagory.id}</td>
<td>${catagory.name}</td>
<td>
<button class="btn btn-primary btnEdit" id="${catagory.id}">Edit</button>
<button class="btn btn-warning btnDelete" id="${catagory.id}">Delete</button>
</td>
</tr>
</s:iterator>
</tbody>
</table>
推荐答案
在准备好文档后,将所有带有"btnDelete"类的标签初始化为click函数. 成功执行ajax调用后,您将所有内容替换为服务器的响应. 届时,您将删除所有按钮,并使用新按钮添加新数据.
At document ready you initialize all tags with class "btnDelete" to the click function. When you do a successfully ajax call, you replace all your content with response from the server. At that point you remove all your buttons and add new data with new buttons.
jQuery不会监听这些按钮,因为$(.btnDelete").click(...仅在页面加载时设置.
jQuery is not listening to these buttons because the $(".btnDelete").click(... was only set at page load.
如果您更改
$(".btnDelete").click(function() {
到
$(document).on("click", ".btnDelete", function() {
将新数据添加到.container后,它仍然可以工作 当您动态添加带有类".btnDelete"的新标签时,"on"功能也会触发(请参见此处 )
it will still work after you add new data to .container The "on" function also triggers when you dynamically add new tags with class ".btnDelete" (See here)
这篇关于附加html数据时不能多次单击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!