在执行 onclick 函数之前禁用元素属性 [英] Disable element attribute before onclick function is executed

查看:29
本文介绍了在执行 onclick 函数之前禁用元素属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Angular 中的指令禁用双击按钮.

I am trying to disable double clicking buttons using directives in Angular.

这是我的相关模板代码:

Here is my relevant template code:

<button (click)="onClickFunction()" appPreventDoubleClick>Add</button>

这是我的指令:

@Directive({
  selector: "[appPreventDoubleClick]"
})
export class PreventDoubleClickDirective {
  count: number = 0;
  constructor() {}

  @HostListener("click", ["$event"])
  click(event) {
    ++this.count;
    if (this.count > 1) {
      console.log("disabling");
      event.srcElement.setAttribute("disabled",true);
      setTimeout(() => {
        event.srcElement.removeAttribute("disabled");
        this.count = 0;
      }, 1000);
    }
  }
}

我基本上要做的是禁用一个按钮,如果它被点击两次并在 1 秒后重置它,这样 onClickFunction() 如果它被禁用就不会被调用.但实际情况是,尽管 @HostListener click() 函数在 onClickFunction() 之前被调用,但 onClickFunction() 仍在执行.我怎么解决这个问题?任何帮助表示赞赏.

What I'm basically trying to do is disable a button if it's clicked twice and reset it after 1 second so that onClickFunction() won't be called if it is disabled. But what's happening is that although the @HostListener click() function is being called before onClickFunction(), onClickFunction() is still executing. How can I solve this problem? Any help is appreciated.

编辑:根据评论,我想提一下我已经尝试过这个:

Edit: As per the comment, I wanted to mention that I had tried this first:

@HostListener("click", ["$event"])
click(event) {
  event.srcElement.setAttribute("disabled", true);
  setTimeout(() => {
    event.srcElement.removeAttribute("disabled");
  }, 1000);
}

但这要视具体情况而定,因为在某些情况下,即使在第一次调用该函数之前,该按钮就已被禁用.我想找到一个适用于任何地方的通用解决方案.谁能告诉我为什么会发生这种不匹配,我能做些什么来解决这个问题?提前致谢.

But this works on a case-by-case basis, as in some cases the button is disabled even before the function is called the very first time. I want to find a generic solution that works everywhere. Can anyone tell me why this mismatch occurs, and what I can do to fix this? Thanks in advance.

推荐答案

好的.我找到了这个问题的解决方案.这是我的指令和更新后的代码.

Alright. I found a solution for this issue. Here is my directive with the updated code.

@Directive({
  selector: "[appPreventDoubleClick]"
})
export class PreventDoubleClickDirective {
  constructor() {}

  @HostListener("click", ["$event"])
  click(event) {
    setTimeout(() => {
      event.srcElement.setAttribute("disabled", true);
    }, 0);
    setTimeout(() => {
      event.srcElement.removeAttribute("disabled");
    }, 1000);
  }
}

我不太确定为什么会这样,希望你们中的一些人有更好的理解.

I'm not exactly sure why this works, hope some of you have a better understanding.

这篇关于在执行 onclick 函数之前禁用元素属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆