jQuery:使用动态添加的按钮删除最近的按钮

时间:2013-01-25 11:32:24

标签: 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();      
});

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>

5 个答案:

答案 0 :(得分:5)

试试这个(Works in 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 eventwindow load event,则点击事件不会触发。
不在DOM内部http://jsfiddle.net/mkqU2/2/

答案 1 :(得分:0)

无需更改您的代码,工作正常:

http://jsfiddle.net/yAMjj/

问题似乎是您的表没有正确的ID。确保它是

<table id="officers-table">

答案 2 :(得分:0)

尝试

$(this).parent('tr').remove();

$(this).parent().remove();

答案 3 :(得分:0)

这个答案有点超出了问题的范围,但这里的答案指出了我正确的方向,所以我想回馈一些东西。

这是我在ajax成功结果后删除它所做的简单版本,我发现ajax结果部分中的$(this)没有删除该行,我想在那一点上它可能是那个&#34;这个&#34;是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();
       }
     }
   });
  }
});

答案 4 :(得分:-1)

$(whichtr).remove()?这会有用吗?