如何在javascript中使用另一个按钮来防止按钮上的点击事件触发?

我有一个带有id“myButton”的按钮,当点击它时,它应该每次增加id“clickCount”的span中的计数1,另一个按钮有一个id“deactivate”,当点击时,它应该不再允许计数的增加,即使点击id为“myButton”的按钮,我可以管理到计数的增加, 但不知道如何在不禁用第一个按钮的情况下阻止计数增加。


断续器


<button id="myButton">Click me!</button>

<p>You clicked on the button <span id="clickCount">0</span> times</p>

<button id="deactivate">Désactivate counting</button>

Javascript


let myButton = document.getElementById('myButton');

let newCount = document.getElementById('clickCount');

let deact = document.getElementById('deactivate');

let count = 0;

 myButton.addEventListener("click", function() {

 count++;

 newCount.innerText = count;

});


RISEBY
浏览 128回答 2
2回答

米脂

您可以添加 在停用时更改为 true 的 ,并在它为 false 时允许递增:booleanlet myButton = document.getElementById('myButton');let newCount = document.getElementById('clickCount');let deact = document.getElementById('deactivate');let count = 0;let deactivated = false;deact.addEventListener("click", function(){&nbsp; &nbsp; &nbsp;deactivated = true;});myButton.addEventListener("click", function() {&nbsp; &nbsp; &nbsp;if(!deactivated){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newCount.innerText = count;&nbsp; &nbsp; &nbsp;}});<button id="myButton">Click me!</button><p>You clicked on the button <span id="clickCount">0</span> times</p><button id="deactivate">Désactivate counting</button>

慕桂英546537

从单击其他按钮时删除事件侦听器#myButtonlet myButton = document.getElementById('myButton');let newCount = document.getElementById('clickCount');let deact = document.getElementById('deactivate');let count = 0;function handler() {&nbsp; count++;&nbsp; newCount.innerText = count;}myButton.addEventListener('click', handler);deact.addEventListener('click', () => myButton.removeEventListener('click', handler));<button id="myButton">Click me!</button><p>You clicked on the button <span id="clickCount">0</span> times</p><button id="deactivate">Désactivate counting</button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript