简体   繁体   中英

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:

<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?

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.

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.

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

You can use Element.currentTarget.setAttribute(name, value) method more details about the function here .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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