首页 > 解决方案 > 如何更改选定行的最后一个单元格的 innerHTML?

问题描述

我有两张桌子。当用户单击“添加”按钮时,该行将被添加到另一个表中。而在另一个表中,当用户单击“删除”按钮时,该行将被添加到前一个表中。我的这部分工作正常。

问题是我需要在更改表格时更改行的按钮。当一行从“添加”表转到“删除”表时,按钮需要从“添加”传递到“删除”。

这是一张图片,以便您更好地理解:

在此处输入图像描述

我的代码是这个:

$(document).ready(function(){

    $(".agregar").on("click", function(event){
        event.preventDefault();

        var row = $(this).parents('tr');

        //$(this).parents('tr').find('td:last-child').val();

        $('#tablaSala').append(row);
    });

   $(".borrar").on("click", function(event){
        event.preventDefault();

        var row = $(this).parents('tr');

        $('#tablaDisponibles').append(row);
    });
});

在将行放在另一张表上之前,我需要编辑最后一个单元格。

这将是按钮的代码

//add button
<button class="btn agregar"><span class="glyphicon glyphicon-plus"></span></button>

//delete button
<button class="btn borrar"><span class="glyphicon glyphicon-trash"></span></button>

标签: javascriptjqueryhtmlhtml-table

解决方案


有很多方法可以做到这一点。

一种方法是在所有行中都有两个按钮并使用 CSS 隐藏一个或另一个。

例如:

.table_1 .borrar { display:none; }
.table_2 .agregar { display:none; }

根据信息,您可能不希望人们打开检查器,显示按钮并单击它。没什么大不了的,但就像我说的,这取决于你用它做什么。

如果要对其进行编码,则必须在添加按钮之前对其进行修改。

像这样的东西

var row = $(this).closest('tr');
var button = row.find('.btn');
button.removeClass('agregar').addClass('borrar');
button.find('.glyphicon').removeClass('glyphicon-plus').addClass('glyphicon-trash');

但是等等,您原来的“点击”事件仍在被触发。为什么?因为即使你交换了类,你也已经为它们中的每一个附加了一个方法。

为了使您的新按钮起作用,您需要附加这样的方法

$("body").on("click", ".agregar", function(event){ ... }
$("body").on("click", ".borrar", function(event){ ... }

这将告诉代码在每个新添加的 .agregar 和 .borrar 元素事件上运行。

这是一个例子

$(document).ready(function() {

  $("body").on("click", ".agregar", function(event) {
    event.preventDefault();

    var row = $(this).parents('tr');

    var button = row.find('.btn');
    button.removeClass('agregar').addClass('borrar');
    button.find('.glyphicon').removeClass('glyphicon-plus').addClass('glyphicon-trash');

    $('#tablaSala').append(row);
  });

  $("body").on("click", ".borrar", function(event) {
    event.preventDefault();

    var row = $(this).parents('tr');
    
    var button = row.find('.btn');
    button.removeClass('borrar').addClass('agregar');
    button.find('.glyphicon').removeClass('glyphicon-trash').addClass('glyphicon-plus');

    $('#tablaDisponibles').append(row);
  });
});
table {
  margin-bottom: 40px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tablaDisponibles" border="1">
  <tr>
    <td>Row 1</td>
    <td><button class="btn agregar"><span class="glyphicon glyphicon-plus"></span></button></td>
  </tr>
</table>

<table id="tablaSala" border="1">
  <tr>
    <td>Row 2</td>
    <td><button class="btn borrar"><span class="glyphicon glyphicon-trash"></span></button></td>
  </tr>
</table>


推荐阅读