简体   繁体   English

如何使用 JavaScript addEventListener() 方法禁用按钮?

[英]how to disable button using JavaScript addEventListener() method?

I was looking for how to disable button using JS and I find this and it works:我一直在寻找如何使用 JS 禁用按钮,我找到了这个并且它有效:

<button id="startbtn" onclick="this.disabled=true; pausebtn.disabled=false; stopbtn.disabled=false;">Start</button>

but I want to disable it using addEventListener() method instead of doing it directly on the html div, but it is not working, is it posible?但我想使用 addEventListener() 方法禁用它,而不是直接在 html div 上禁用它,但它不起作用,是否可行?

let start1 = document.getElementById('startbtn');
        start1.addEventListener('click', start);
        start1.addEventListener('click', this.disabled = true);

Obs: the second line in the code above starts the "start" function which is a cronometer. Obs:上面代码中的第二行启动了“start”function,这是一个计时表。

You need to pass a callback.你需要传递一个回调。

If you didn't already have a reference to the button use the currentTarget property of the event object that gets passed into the callback.如果您还没有对按钮的引用,请使用传递到回调中的事件 object 的currentTarget属性。

start1.addEventListener('click',() => start1.disabled = true);

You can use Element.currentTarget.setAttribute(name, value) method more details about the function here .您可以在此处使用Element.currentTarget.setAttribute(name, value)方法了解有关 function 的更多详细信息。

let start1 = document.getElementById('startbtn');
start1.addEventListener('click', start);
start1.addEventListener('click', (e) => e.currentTarget.setAttribute('disabled', true));

It is tested & working.它已经过测试和工作。
let me know if you have any issues with the snippet above.如果您对上面的代码片段有任何问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM