使用contextmenu获取所选行的数据

时间:2017-06-07 15:18:01

标签: php jquery contextmenu codeigniter-3 jquery-ui-contextmenu

我想使用 Jquery contextmenu onclick事件来编辑/删除表格中的一行数据。问题是,当我单击一行时,将获取最后一行而不是所选行。

表:

<table id="ppmpsupplies" class="table table-bordered table-hover" cellspacing="0" width="100%">
          <thead>
            <tr>
              <th>Code</th>
              <th>General Description</th>
              <th>Unit</th>
              <th>Quantity</th>
              <th>Estimated Budget</th>
              <th>Mode of Procurement</th>                  

            </tr>
          </thead>
          <tbody>
            <?php foreach($items as $item){?>
            <tr>
             <td><?php echo $item->id;?></td>
             <td><?php echo $item->description;?></td>
             <td><?php echo $item->unit;?></td>
             <td><?php echo $item->quantity;?></td>
             <td><?php echo $item->budget;?></td>
             <td><?php echo $item->mode;?></td>                     
          </tr>
          <?php }?>

        </tbody>
        <tfoot>
          <td colspan="3"></td>
          <td>Total</td>
          <td></td>
        </tfoot>
      </table>

上下文菜单:

                        sep3: "----",
                        "edit": {
                          name: "Edit",
                          icon: "fa-pencil-square-o",
                          callback: function(itemKey, options) {
                            $('#ppmpsupplies tbody tr').on('click', edit_item(<?php print $item->id ?>));
                            // var m = "clicked: " + itemKey;
                            // window.console && console.log(m) || alert(m);
                            return true;
                          }
                        },
                        sep4: "----",
                        "delete": {
                          name: "Delete",
                          icon: "fa-trash-o",
                          callback: function(itemKey, options) {
                            $('#ppmpsupplies tbody tr').on('click', delete_item(<?php print $item->id ?>));                                 
                            return true;
                          }
                        },

source

1 个答案:

答案 0 :(得分:1)

使用data-*属性在JS代码中传递要编辑/删除的ID。

更改以下内容。

自:

<tbody>
<?php foreach($items as $item){?>
<tr>

<tbody>
<?php foreach($items as $item){?>
<tr data-id="<php print $item->id?>">

然后更新您的JS以提取.data('id')值。

更改以下内容。

自:

// Edit
$('#ppmpsupplies tbody tr').on('click', edit_item(<?php print $item->id ?>));

// Delete
$('#ppmpsupplies tbody tr').on('click', delete_item(<?php print $item->id ?>));

要:

// Edit
var that = $(this);
$('#ppmpsupplies tbody tr').on('click', edit_item(that.data('id')));

// Delete
var that = $(this);
$('#ppmpsupplies tbody tr').on('click', delete_item(that.data('id')));