我正在用 Jquery 设计一个 html 表,它只编辑记录或在编辑时简单地取消,这是我的问题开始的地方。我唯一的愿望是按下取消按钮将数据恢复到以前的状态,例如:
在我的表中,我不小心删除了姓氏“Sanchez”。然后我只需按下取消按钮,它就会在我的记录中返回姓氏“Sanchez”,就好像它没有被编辑过一样。
在我的“取消”按钮中,它只执行禁用“true”中的输入,没有别的,因为我不知道如何返回意外编辑的数据。
我向您展示我的代码,以便您可以帮助我:
$("#Editar1").click(function(){
$("#nombre1").prop("disabled", false);
$("#apellido1").prop("disabled", false);
});
$("#Cancelar1").click(function(){
$("#nombre1").prop("disabled", true);
$("#apellido1").prop("disabled", true);
});
$("#Editar2").click(function(){
$("#nombre2").prop("disabled", false);
$("#apellido2").prop("disabled", false);
});
$("#Cancelar2").click(function(){
$("#nombre2").prop("disabled", true);
$("#apellido2").prop("disabled", true);
});
$("#Editar3").click(function(){
$("#nombre3").prop("disabled", false);
$("#apellido3").prop("disabled", false);
});
$("#Cancelar3").click(function(){
$("#nombre3").prop("disabled", true);
$("#apellido3").prop("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border=1 >
<thead>
<tr>
<th>Id</th><th>Col 2</th><th>Col 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><input id="nombre1" disabled value="Juan"></td>
<td><input id="apellido1" disabled value="sanchez"></td>
<td><button id="Editar1">Editar</button></td>
<td><button id="Cancelar1">Cancelar</button></td>
</tr>
<tr>
<td>2</td><td><input id="nombre2" disabled value="Joanna"></td><td><input id="apellido2" disabled value="herrera"></td>
<td><button id="Editar2">Editar</button></td>
<td><button id="Cancelar2">Cancelar</button></td>
</tr>
<tr>
<td>3</td><td><input id="nombre3" disabled value="Marcos"></td><td><input id="apellido3" disabled value="lopez"></td>
<td><button id="Editar3">Editar</button></td>
<td><button id="Cancelar3">Cancelar</button></td>
</tr>
</tbody>
</table>
我希望你能帮助我,谢谢。
首先,您应该使用类而不是 ID,以避免重复代码。关于您的问题,您可以使用包含文本的跨度。当您按下“编辑”时,您会隐藏跨度并显示输入。如果按取消,您只需隐藏输入并显示原始跨度。您还需要一个“保存”按钮来更改跨度的文本并隐藏输入。
像这样的东西:
我已经更改了 html 和 JQuery 中的一些内容,这些内容从使用您用来将 click 函数分配给它
class
作为第一步分配的函数的 id 开始。因此,使用.data()函数在修改之前保存值,以便如果您取消操作它会返回到原始值,在此示例value
中用作保存值的键。其余的在代码中解释。我希望它对你有帮助。您必须在编辑它们之前保存它们。这样价值就不会丢失。我只是用名字做的,但你明白了。
我会改变一些事情:
input
同一行中的那些,所以我没有为每个按钮使用一个 id,而是使用 aclass
来标识按钮并为所有具有此属性的按钮分配一个功能class
input
,这样我就可以控制正在更改的内容。tr
)的行并查找input
启用或禁用它们的元素完成上述所有操作后,您将获得易于阅读和维护的更简洁的代码。
PS:jQuery 可以选择以 HTML 元素作为目标来处理对象上的事件,因此您只使用一个事件而不是每个要执行相同操作的元素的事件$( selector ).on( event , target , function to调用)示例:
编辑后的代码如下:
您几乎拥有它!...
<form>
具有属性的帐户的元素defaultValue
,有了这个,您可以在按下按钮cancelar
时返回到修改前的默认值。从你的代码开始,我给你一个如何做的例子