当我编写这段代码时,我有两个警告“在闭包中使用此内容”
function tableIntoJson(){
var tableArray = [];
var columnIndex=0;
var rowIndex=0;
$('table#editable tr:not(#head)').each(function() {
var tableData = $(this).find('td:not(#head)');
tableArray[rowIndex]=[];
if (tableData.length > 0) {
columnIndex=0;
tableData.each(function() {
tableArray[rowIndex][columnIndex]=$(this).text();
columnIndex++
});
}
rowIndex++;
});
var jsonString=JSON.stringify(tableArray);
return jsonString;
}
警告让我烦恼))。我如何替换“$(this)”?
最佳答案
即使这是 this
的有效使用,但如果您想让您的 IDE 满意,请替换
$('table#editable tr:not(#head)').each(function() {
var tableData = $(this).find('td:not(#head)');
与
$('table#editable tr:not(#head)').each(function(trIndex, tr) {
var tableData = $(tr).find('td:not(#head)');
(下一个 .each
类似)。
它也比使用 this
更具可读性,因为通过这种方式,您可以明确地知道每个循环迭代的内容。
关于javascript - 避免警告 "Use of this in closure",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23124528/