我无法使用动态生成的按钮删除表中的行。主要问题是"alert()"不起作用。如何捕获"点击"事件?
j查询:
$("#officers-table").on('click', '.remove-officer-button', function(e) {
var whichtr = $(this).closest("tr");
alert('worked'); // Alert does not work
whichtr.remove();
});
HTML/PHP (更新了代码)
<table id="officers-table" class="ui-widget ui-widget-content">
<?php if($num_officers > 0): ?>
<thead>
<tr class="ui-widget-header ">
<th>Name</th>
<th>Director</th>
<th>Shareholder</th>
<th>Secretary</th>
<th colspan="2">Options</th>
</tr>
</thead>
<?php endif; ?>
<tbody>
<?php foreach ($officers as $item): ?>
<tr>
<td><?=$item->name?> <?=$item->lastname?></td>
<td><?=$item->is_director?></td>
<td><?=$item->is_shareholder?></td>
<td><?=$item->is_secretary?></td>
<td>Edit</td>
<td><button type="button" value="<?=$item->id?>" class="remove-officer-button">Remove</button></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
试试这个(在JSFiddle中工作):
$(".remove-officer-button").on('click', function(e) {
var whichtr = $(this).closest("tr");
alert('worked'); // Alert does not work
whichtr.remove();
});
编辑
正如大家所说,您的代码似乎可以正常工作。检查此 JSFiddle:
原始代码:http://jsfiddle.net/mkqU2/1/
您可以使用上面的代码作为替代方法,但听起来您还有其他一些 javascript 错误导致脚本中断。
也。。确保代码位于 DOM Ready 事件中。如果不是,则单击该按钮时没有任何反应。
下面的jsfiddle复制了您的错误,如果未包装在DOM Ready event
中,则单击事件不会触发,否则window load event
。
未在 DOM 内部准备就绪:http://jsfiddle.net/mkqU2/2/
无需更改代码,代码工作正常:
http://jsfiddle.net/yAMjj/
问题似乎是您的表没有正确的 ID。 确保它是
<table id="officers-table">
尝试
$(this).parent('tr').remove();
或
$(this).parent().remove();
这个答案有点超出问题的范围,但这里的答案为我指明了正确的方向,所以我想回馈一些东西。
这是我在成功的 ajax 结果后对它所做的删除的简单版本,我发现 ajax 结果部分中的 $(this) 没有删除该行,我认为此时可能是"this"要么是 ajax 对象,要么是成功属性,而不是按钮。
// 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();
}
}
});
}
});
$(whichtr).remove() ?这行得通吗?