如何让jQuery.change()引用Handontable上的单元格

How to get jQuery .change() to reference cell on a Handsontable?

本文关键字:Handontable 引用 单元格 jQuery change      更新时间:2023-09-26

尝试执行:我想将Handontable上的用户更改保存到数据库中。我认为我可以做的一种方法是创建一个隐藏的html表单,其中表单输入被引用到Handontable中的特定单元格。

问题:在.change函数中,我无法引用Handontable中的特定单元格。

我在下面尝试过的:试图获取用户对单元格行(2)列(2)所做的任何更改,并将html表单id row2col2formInput更改为该值。

    <script>
            //fetch handsontable input for row 2 colum 2 and change corresponding hidden form input
            $("#example").handsontable.(data[2][2]).change(function() {
                $("#row2col2formInput").val($(this).val());
            });

$(document).ready(function () {

  var
 data = [
    ['', 'Kia', 'Nissan', 'Toyota', 'Honda'],
    ['2008', 10, 11, 12, 13],
    ['2009', 20, 11, 14, 13],
    ['2010', 30, 15, 12, 13]
  ],
    container = document.getElementById('example'),
    hot;  

  hot = new Handsontable(container, {
    data: data,
    minSpareRows: 1,
    colHeaders: true,
    contextMenu: true
  });

});

</script> 

首先,引用单元格的行是错误的,这是正确的。而且你不能完全按照你的方式引用一个单元格。无论如何,你不应该这样做。

这是实现这项任务的另一种方法,顺便说一句,这是我们大多数使用HOT的人无论如何都会做的事情。

我不知道你的数据库结构,所以很难说,所以假设你使用的是SQL,每一行都是数据库中某个表上的物理行。现在,正如您所知,SQL中的每一行都应该有一个唯一的主自动递增键,您可以使用它来引用行,当您开始在HOT中对行进行混洗时,这会很有用。

现在让我们假设您有一个简单的JS和您所描述的HOT实例。data对象是向HOT实例提供数据的对象,但更重要的是,它是一个高度可变的对象。当用户对单元格进行更改时,此对象会发生突变。

这意味着你可以在某个地方添加一个Submit按钮,在那个时候获取对象并将其发送到你的数据库。这是一种经常使用的方法。以下是唯一的SQL id的用武之地。您的data对象可能会将此ID附加到现有行中,并使其成为隐藏列(无需向用户显示此信息)。

如果用户创建了一个新行,那么您可以附加一个负递减的整数(表示数据库中的"新"行),当用户提交时,您只需遍历data对象,并对ID为正的行执行UPDATE,对ID为负的行执行INSERT。

仅此而已。另一个选项是,您可以使用afterChange事件在每次更改时自动保存到DB中。你的函数会显示类似的内容

afterChange: function(changes, source) {
    // changes is an array of changes, where each change has 4 values, in order:
    // row index, col index, old value, new value
    changes.forEach(function(change) {
        var row = change[0];
        var col = change[1];
        var newVal = change[3];
        var hiddenIdIndex = data[row].length - 1; // put the hidden id always at the end
        var hiddenID = data[row][hiddenIdIndex];
        // make a call to your function which talks to the SQL db
        saveToDB(hiddenID, col, newVal);
        // in the function, you could first see if the ID exists in the system.
        // If it does, do an UPDATE using the newVal and the column name, or
        // simply suply this function with the entire row (data[row]). If it
        // doesn't exist, do an INSERT with the data[row].
    })
}

希望这能有所帮助!