如果 colmodel 中的名称是整数,我如何在 jqGrid 中设置单元格?

How can I set the cell in a jqGrid if the name in colmodel is an integer?

当 colmodel 中的名称是整数时,jqgrid setcell 会导致问题。它给出错误:

Uncaught TypeError: Cannot read property 'formatter' of undefined.

我添加 grid.locale-en.jsjqgrid-min.js 的顺序是正确的。

准确地说,错误在行中:

var h = a.p.colModel[e]; if (h.formatter !== void 0) 

in jqgrid-min.js 其中 e colmodel 名称(注意这是一个整数)。

这是我设置单元格的方式。

$("#GoingCostLogGrid").jqGrid('setCell', rowId, Costs_ProjectOrProgram , cellValue_CurrentTotalforAllFY);

其中 Costs_ProjectOrProgram 是一个整数,也是 colmodel 中的列名。

很大的不同如果你用数字(比如12)作为参数调用setCell或者用包含数字的字符串(比如"12").数字参数将被解释为colModel数组中的索引,但字符串值将被解释为列名.

因此,如果 Costs_ProjectOrProgram 的类型是数字,而您想将其解释为字符串,那么您应该将变量转换为字符串。所以你应该使用

$("#GoingCostLogGrid").jqGrid('setCell', rowId, String(Costs_ProjectOrProgram),
    cellValue_CurrentTotalforAllFY);

而不是

$("#GoingCostLogGrid").jqGrid('setCell', rowId, Costs_ProjectOrProgram,
    cellValue_CurrentTotalforAllFY);

顺便说一下,使用第一个大写字符的变量是非常糟糕的。对应于JavaScript的名称转换,应该使用这样的名称only for constructors(class的构造函数)。它可以很容易地看到如何使用标识符。例如,您需要使用 var d = new Date(2015, 3, 24); 而不是 var d = Date(2015, 3, 24);,即使您在上述使用 Date 的情况下可能在许多网络浏览器中获得相同的结果。你可以看到,甚至 JavaScript 代码的格式化程序也以另一种颜色显示具有第一个大写字符的标识,以强调它具有 另一个含义 作为标准变量(例如 cellValue_CurrentTotalforAllFY)。我强烈建议您保留您使用的语言中存在的名称转换。

UPDATED:jqGrid 执行以下操作:在 setCell 代码的开头,它尝试使用 isNaN(colname) 将列名参数转换为数字。如果列名是数字或包含数字的字符串,那么它将被解释为作为列的索引(参见the lines)。所以要解决这个问题,你必须使用 setCellgetCellgetCol 和许多其他方法,使用列的索引而不是名称。所以你必须做以下事情

var colModel = $("#GoingCostLogGrid").jqGrid("getGridParam", "colModel"),
    iCol, nCol = colModel.length; 

for (iCol = 0; iCol < nCol; iCol++) {
    if (colModel[iCol].name === Costs_ProjectOrProgram) {
        $("#GoingCostLogGrid").jqGrid("setCell", rowId, iCol,
            cellValue_CurrentTotalforAllFY);
    }
}

如果你有很多地方需要做同样的事情,那么你可以将按列名搜索列索引放在函数中,并在需要时调用。

如果您想使用 free jqGrid instead of jqGrid 4.6 then you can use jsonmap even in case of usage datatype: "local". See the wiki article 了解更多详情。在这种情况下,您可以将列定义为 {name: "c5", jsonmap: "5"} 而不是用法 {name: "5"} 并且会出现上述问题。或者,您可以更改输入数据,使输入数据的属性以字母开头。