首页 > 解决方案 > 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);

但没有运气。如果有人可以帮助我,甚至为我提供一些建议或文件,将不胜感激。

标签: javascriptjquerydatatables

解决方案


您必须使用两个不同且独立的函数,使用外部变量来连接它们;您不能以嵌套方式使用 .on()


推荐阅读