how to stop writing text on innerhtml by clicking buttuon
To stop writing text on innerHTML by clicking a button, you can remove the event listener that is responsible for writing the text. Here is an example:
HTML:
<button id="write-btn">Write Text</button>
JavaScript:
const writeBtn = document.getElementById('write-btn');
let textWritten = false;
function writeText() {
const output = document.getElementById('output');
output.innerHTML = 'Some text.';
textWritten = true;
}
writeBtn.addEventListener('click', writeText);
function stopWritingText() {
if (textWritten) {
const output = document.getElementById('output');
output.innerHTML = '';
textWritten = false;
writeBtn.removeEventListener('click', writeText);
}
}
writeBtn.addEventListener('click', stopWritingText);
In this example, we have a button with an ID of "write-btn" that initially has an event listener attached to it that writes some text to an element with an ID of "output" when clicked. We also have a variable called "textWritten" that keeps track of whether the text has been written.
We then add another event listener to the button that calls the "stopWritingText" function when clicked. This function checks if the text has been written and, if so, removes the text from the "output" element, sets "textWritten" to false, and removes the original event listener that wrote the text.
Now, when the button is clicked, it will write the text as usual. But when clicked again, it will remove the text and stop writing it on subsequent clicks.
原文地址: https://www.cveoy.top/t/topic/bcNP 著作权归作者所有。请勿转载和采集!