Php jQuery:删除最近的<;tr>;带有动态添加的按钮
我无法使用动态生成的按钮删除表中的行。 主要问题是“alert()”不起作用。 如何捕捉“点击”事件 jQuery:Php jQuery:删除最近的<;tr>;带有动态添加的按钮,php,jquery,html,button,onclick,Php,Jquery,Html,Button,Onclick,我无法使用动态生成的按钮删除表中的行。 主要问题是“alert()”不起作用。 如何捕捉“点击”事件 jQuery: $("#officers-table").on('click', '.remove-officer-button', function(e) { var whichtr = $(this).closest("tr"); alert('worked'); // Alert does not work whichtr.remove(); });
$("#officers-table").on('click', '.remove-officer-button', function(e) {
var whichtr = $(this).closest("tr");
alert('worked'); // Alert does not work
whichtr.remove();
});
HTML/PHP(更新了代码)
名称
经理
股东
秘书
选择权
编辑
$(whichtr.remove()?这样行吗 试试这个():
编辑
正如大家所说的,您的代码似乎工作正常。检查此JSFIDLE:
原始代码:
您可以使用上面的代码作为替代,但听起来好像有其他javascript错误导致脚本中断
还有。。确保您的代码在DOM就绪事件中。如果不是,则单击按钮时不会发生任何事情。
下面的JSFIDLE复制您的错误,如果没有包装在DOM就绪事件
或窗口加载事件
中,则不会触发click事件
不在DOM Ready内部:无需修改代码,代码运行良好:
问题似乎是您的表没有正确的ID。请确保它是正确的
<table id="officers-table">
试试看
$(this.parent('tr').remove()代码>
或
$(this.parent().remove()代码>这个答案有点超出了问题的范围,但这里的答案为我指明了正确的方向,所以我想回馈一些东西
这是一个简单的版本,在成功的ajax结果之后,我用它删除了,我在ajax结果部分发现$(This)没有删除行,我认为在这一点上,“This”可能是ajax对象或success属性,而不是按钮
// My button markup ends up like this with php echoing out the id numbers.
// one button in each row.
<button type="button" id="delete234" value="234">Delete</button>
$('button[id^=\'delete\']').on('click', function() {
if (confirm('Are you sure?')) {
var node = this;
$.ajax({
url: 'http://example.com/somewhere.php?somethingtodelete=' + $(node).val(),
dataType: 'json',
success: function (json) {
if (json['success']) {
$(node).closest('tr').remove();
}
}
});
}
});
//我的按钮标记是这样结束的,php会回显id号。
//每行一个按钮。
删除
$('button[id^=\'delete\']')。在('click',function()上{
如果(确认('你确定吗?')){
var节点=这个;
$.ajax({
网址:'http://example.com/somewhere.php?somethingtodelete='+$(节点).val(),
数据类型:“json”,
成功:函数(json){
if(json['success']){
$(node).closest('tr').remove();
}
}
});
}
});
你;你可能会出错。检查您的JS控制台。控制台不会显示任何错误。单击事件是否会触发?$(“#军官表”)
可能为空。你确定你有一个ID为的元素吗?检查你的表是否真的有ID=“officers table”
属性,而该属性已经是jQuery对象了。。不需要在$
内再次传递它,这不是重点。警报不起作用,因此我没有捕获我的单击事件。我不应该使用“this”-我想我必须改用e.target。这与问题中的代码不同,它没有被破坏。函数(e)您可以删除“e”,因为我们在此代码中没有使用它,或者如果我们不打算使用它。:)
<table id="officers-table">
// My button markup ends up like this with php echoing out the id numbers.
// one button in each row.
<button type="button" id="delete234" value="234">Delete</button>
$('button[id^=\'delete\']').on('click', function() {
if (confirm('Are you sure?')) {
var node = this;
$.ajax({
url: 'http://example.com/somewhere.php?somethingtodelete=' + $(node).val(),
dataType: 'json',
success: function (json) {
if (json['success']) {
$(node).closest('tr').remove();
}
}
});
}
});