我有兩個事件偵聽器,它們都根據視頻狀態在頁面加載時觸發。但如果兩者都被解雇,我希望第一個停止運行。這怎么可能?
obj.addEventListener('suspend', () => {
// when only this is fired -> run this code
// my code
});
obj.addEventListener('play', () => {
// when this is fired too -> run this code and deactivate the first code
// my code
});
uj5u.com熱心網友回復:
您需要定義一個全域變數并檢查它是否為 true ,而不是觸發第一個函式。但是可能存在一些運行時問題,如果在運行第一個事件之間,呼叫第二個事件,第一個事件不會凍結并繼續運行。
let shouldRun = true;
obj.addEventListener('suspend', () => {
// when only this is fired -> run this code
if(!shouldRun){
return;
}
// my code
});
obj.addEventListener('play', () => {
// when this is fired too -> run this code and deactivate the first code
shouldRun = false;
// my code
});
uj5u.com熱心網友回復:
我猜您可以嘗試在 Call of 'play' 事件上使用 obj.removeEventListener('suspend') 。
有關 removeEventListener 的更多資訊,您可以通過官方鏈接。 https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
uj5u.com熱心網友回復:
解決此問題的一個簡單方法是使用removeEventListener().
function handleSuspend() {
// when only this is fired -> run this code
// my code
}
function handlePlay() {
// when this is fired too -> run this code and deactivate the first code
obj.removeEventListener('suspend', handleSuspend);
// my code
}
obj.addEventListener('suspend', handleSuspend);
obj.addEventListener('play', handlePlay);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376175.html
標籤:javascript 功能 添加事件监听器
上一篇:減少A到Z字母集的函式數量
