簡體   English   中英

為什么 addEventListener 觸發事件

[英]why addEventListener fire the event

addNode_button 點擊事件處理程序正在等待輸入做某事。 但我想通過按 esc 來停止事件監聽器。 我做了一個簡化的例子,顯示 keydown 中的 addEventListener 觸發按鈕上的“點擊”。 我不明白為什么。

 addNode_but.addEventListener('click',addNodeButClick); function addNodeButClick(){ let value = nodePt_inp.value;out1.value = new Date(); let waitingValue = 'try to stop clock by escape,then input something to stop'; function callMeAgain(){addNode_but.dispatchEvent(new Event('click'))}; switch (value){ case '': nodePt_inp.value = waitingValue; case waitingValue: setTimeout(callMeAgain,100);break; default: out1.value = "only now I've stopped"; } } document.addEventListener('keydown',escape); function escape(evt){ if (evt.key==='Escape'){ addNode_but.removeEventListener('click',addNodeButClick); nodePt_inp.value = ""; addNode_but.addEventListener('click',addNodeButClick); } }
 <input style='display:block;width:60ch' type="text" id="nodePt_inp" name='pt'> <button id='addNode_but' class='button'>clickMe and try to stop by esc</button> <output id='out1'>output</output>

為了停止setTimeout調用,您應該保留對該調用結果的引用並調用clearTimeout

 addNode_but.addEventListener('click',addNodeButClick); var timerId = null; function addNodeButClick(){ let value = nodePt_inp.value;out1.value = new Date(); let waitingValue = 'try to stop clock by escape,then input something to stop'; function callMeAgain(){addNode_but.dispatchEvent(new Event('click'))}; nodePt_inp.value = waitingValue; timerId = setTimeout(callMeAgain,100); } document.addEventListener('keydown',escape); function escape(evt){ if (evt.key==='Escape'){ clearTimeout(timerId); } }
 <input style='display:block;width:60ch' type="text" id="nodePt_inp" name='pt'> <button id='addNode_but' class='button'>clickMe and try to stop by esc</button> <output id='out1'>output</output>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM