1

我有功能,这是代码

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"));

我该如何解决?

4

1 回答 1

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,它可能是您挂钩事件的元素的后代)。

于 2018-06-15T15:29:34.860 回答