【问题标题】:the "this" keyword is disallowed outside of a class body“this”关键字在类主体之外是不允许的
【发布时间】:2018-06-15 15:21:54
【问题描述】:

我有函数,这里是代码

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

我该如何解决?

【问题讨论】:

  • remove_multi_leg 应该作为一些元素事件回调还是作为一些对象方法调用?
  • 这样称呼$(".remove_multi_leg").parent().off("click").on("click", remove_multi_leg);@PatrickEvans
  • 我不明白如何解决它@T.J.Crowder

标签: javascript jquery typescript codacy


【解决方案1】:

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

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 相反,它可能是后代你钩住事件的元素)。

【讨论】:

  • 但是const target是哪种类型?
  • @Balance - TypeScript 会为您推断为EventTarget,这可能是也可能不是您想要的。 :-) 你可以把它转换成HTMLBaseElement,所以const target = (HTMLBaseElement)e.currentTarget;
猜你喜欢
  • 2020-07-24
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
相关资源
最近更新 更多