gpt4 book ai didi

javascript - 如何在js中使用javascript中的外部值创建循环中的对象?

转载 作者:行者123 更新时间:2023-12-03 07:27:33 25 4
gpt4 key购买 nike

我想动态制作一个 jqgrid 列。但我面临一个问题“在外部作用域循环中修改的变量的闭包”。这是我返回 jqgrid 的 colModel 的函数。

 var getJqgridColModel = function () {
var colModel = [
];
//Here i am making the column
if (args && args.colModel) {

for (var i = 0; i < args.colModel.length; i++) {

var col = {
name: "action",
width: "100",
sortable: false,
hidden: false,

formatter: function(cellValue, options, rowObject) {
var markup = "<a class=\"jqGrid-Column-Text\" title=\"%ToolTip%\" href=%Href%;>%Text%</a>";
var replacements = {
//Here is problem
"%Text%": args.colModel[i].actionLink,//Problem occures here.This "args.colModel[i].actionLink" is not recoginize.It shows "closure on a variable modified in loop of outer scope"
"%ToolTip%": "//",
"%Href%": "javascript:PersonSearch.perfomeActionOnSelect(" + rowObject.PersonLog.PersonId + ")"
};

markup = markup.replace(/%\w+%/g, function(all) {
return replacements[all];
});
return markup;
}
};
colModel.push(col);
}

}

return colModel;
}

我该如何解决这个问题?

最佳答案

您原来的示例不起作用的原因是您在循环中创建的所有闭包都引用了同一帧。

    var getJqgridColModel = function () {
var colModel = [];
//Here i am making the column
if (args && args.colModel) {
for (var i = 0; i < args.colModel.length; i++) {

var col = {
name: "action",
width: "100",
sortable: false,
hidden: false,

formatter: (function(i){
return function(cellValue, options, rowObject) {
var markup = "<a class=\"jqGrid-Column-Text\" title=\"%ToolTip%\" href=%Href%;>%Text%</a>";
var replacements = {
//Here is problem
"%Text%": args.colModel[i].actionLink,//Problem occures here.This "args.colModel[i].actionLink" is not recoginize.It shows "closure on a variable modified in loop of outer scope"
"%ToolTip%": "//",
"%Href%": "javascript:PersonSearch.perfomeActionOnSelect(" + rowObject.PersonLog.PersonId + ")"
};

markup = markup.replace(/%\w+%/g, function(all) {
return replacements[all];
});
return markup;
}
}(i));
};
colModel.push(col);
}

}

return colModel;
}

关于javascript - 如何在js中使用javascript中的外部值创建循环中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35938178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com