javascript - JQuery - 为什么这个变量在函数执行后不会丢失它的值?
问题描述
我是 JQuery 的新手,我正在尝试定义一个 JQuery 函数,目的是编辑表格行:模式要求输入新值,然后该函数更新表格行内容。但是,当我选择要编辑的行时,存储该行的变量会“累积”在同一对象中已编辑的所有先前行,并且当我尝试将新值更新到这一行时,所有在接收之前编辑的行并显示相同的值。为什么会这样?
我将向您展示代码:
$("#table").on("click", ".edit", function() {
var table = $("#table").DataTable();
var row = $(this).closest("tr");
//getting the <tr> content with Datatables API:
var values = $table.row(row).data();
$("#name").val(values[0]);
$("#surname").val(values[1]);
$("#city").val(values[2]);
$("#myModal .modal-footer").on("click", "#confirm", function() {
var newValues = []
//getting the <tr> content with Datatables API:
//this alert appears as many time as many rows have been changed
alert($table.row(row).data());
//deleting the old data from the server...
//getting the new values:
newValues.push($("#name").val());
newValues.push($("#surname").val());
newValues.push($("#city").val());
//adding the new date to the server...
$("#myModal").modal("hide");
//update the html table:
table.row(row).data([newValues[0], newValues[1], newValues[2]]);
});
});
正如我之前解释过的,.on("click")
函数中的变量“row”“累积”了之前编辑过的所有行。我认为这是一个范围问题,所以我也尝试调用一个外部函数,它基本上做了同样的事情并利用了这个event.data
对象:
$("#confirm").on("click", {table: table, row: row}, edit);
但没有运气。如果有人可以帮助我,甚至为我提供一些建议或文件,将不胜感激。
解决方案
您必须使用两个不同且独立的函数,使用外部变量来连接它们;您不能以嵌套方式使用 .on()
推荐阅读
- c# - dotnet core web API JSON 响应包含不必要的元素
- c# - 文件激活时 UWP 应用程序冻结在初始屏幕上
- web2py - 使用 auth_membership.group_id 识别特定的组内容
- javascript - 如何允许点击可见性的svg子元素:隐藏?
- python - 使用带有 tf.qint8 输入的量化 Conv2D 时出错
- android - Activity onStart() 操作导致黑屏
- javascript - 为 vuejs 项目导入/导出 javascript 变量
- ubuntu - 有关此命令的详细信息
- c++ - 从 std::vector 的切片中提取一个 int
? - android - 房间搜索查询