【问题标题】:Avoiding warning "Use of this in closure" [duplicate]避免警告“在关闭时使用它”[重复]
【发布时间】:2023-04-10 00:23:01
【问题描述】:

当我编写这段代码时,我有 2 个警告“在闭包中使用它”

 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 没有任何问题。
  • Cloud9 ide 发出此警告
  • 在事件中我可以将 $(this) 替换为 $(event.target) 但我该怎么做呢?

标签: javascript jquery


【解决方案1】:

即使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 更具可读性,因为通过这种方式,您可以明确知道每个循环迭代的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2016-05-05
    • 2020-09-05
    • 1970-01-01
    • 2023-02-03
    相关资源
    最近更新 更多