"这"在类体外不允许使用关键字

时间:2018-06-15 15:21:54

标签: javascript jquery typescript codacy

我有功能,这里是代码

function remove_multi_leg(): void  {
  if (Number($("#search_no_legs").val()) < 2) {
    return;
  }

  const removeId: number = Number($(this).attr("data-number"));
  const highestId: number = Number($("#search_no_legs").val());

  if (removeId === highestId) {
    $(`#multi_leg_${removeId}`).hide();
    $("#search_no_legs").val(highestId);
    return;
  }

  let i: number;
  let end: number;
  let asc : boolean;
  for (i = removeId, end = highestId, asc = removeId <= end; asc ? i <= end : i >= end; asc ? i += 1 : i -= 1) {
    $(`#search_legs_${i}_origin_text`).val($(`#search_legs_${i + 1}_origin_text`).val());
    $(`#search_legs_${i}_origin_id`).val($(`#search_legs_${i + 1}_origin_id`).val());
    $(`#search_legs_${i}_destination_text`).val($(`#search_legs_${i + 1}_destination_text`).val());
    $(`#search_legs_${i}_destination_id`).val($(`#search_legs_${i + 1}_destination_id`).val());
  }
  $(`#multi_leg_${highestId - 1}`).hide();
  $("#search_no_legs").val(highestId - 1);
  return;
}

但是当编码分析代码

时我有奇怪的错误

这是

  

the "this" keyword is disallowed outside of a class body

在这一行

  

const removeId: number = Number($(this).attr("data-number"));

我该如何解决?

1 个答案:

答案 0 :(得分:1)

您可以通过接受参数并使用参数的this属性来重构该函数而不使用currentTarget

function remove_multi_leg(e: Event): void  {
   const target = $(e.currentTarget);
   // ...
   const removeId: number = Number(target.attr("data-number"));
   // ...
}

e的类型可以MouseEvent专门用于click,其中添加了xy。)

currentTargetthis在DOM事件处理程序中引用相同的东西(在正常的过程中),它是您挂起事件的元素(而不是e.target ,它可能是你挂钩事件的元素的后代。)