我有一個函式 A 來選擇.current
元素并對它做一些事情。然后,(重新)將.current
類名移動到另一個元素并對其執行相同的操作。
function funA () {
let state = [];
let currentRow = document.querySelector(".current");
//...
evaluateThings(function () {
currentRow.classList.remove("current");
currentRow.nextSibling.classList.add("current");
funcA();
});
}
function evaluateThings(callback) {
//...
callback()
}
funcA()
問題是,記住以前的選擇器并對新的和最后一個funcA
選擇器進行更改.current
這是一個演示
uj5u.com熱心網友回復:
funcA
向檔案添加一個 keydown 偵聽器。當您遞回呼叫時funcA
,您并沒有洗掉前一個偵聽器,因此在下一個事件中,兩者都運行,并且兩個元素都被更改 - 回圈繼續。
在進行遞回呼叫時洗掉先前的偵聽器。
function funcA() {
const currentRow = document.querySelector(".current");
const handler = (e) => {
if (e.key === 'Enter') {
currentRow.nextElementSibling.classList.add("current");
currentRow.classList.remove("current");
document.removeEventListener("keydown", handler);
evaluateThings(funcA);
} else {
currentRow.innerHTML = e.key
}
};
document.addEventListener("keydown", handler);
}
function evaluateThings(callback) {
//...
callback()
}
funcA()
<div class="row current">a</div>
<div class="row">b</div>
<div class="row">c</div>
<div class="row">d</div>
<div class="row">e</div>
<div class="row"></div>
或者保持監聽器連接,但重新分配指向元素的變數。
let currentRow = document.querySelector(".current");
function funcA() {
document.addEventListener("keydown", (e) => {
if (e.key === 'Enter') {
currentRow.nextElementSibling.classList.add("current");
currentRow.classList.remove("current");
evaluateThings(() => currentRow = document.querySelector(".current"));
} else {
currentRow.innerHTML = e.key;
}
});
}
function evaluateThings(callback) {
//...
callback()
}
funcA()
<div class="row current">a</div>
<div class="row">b</div>
<div class="row">c</div>
<div class="row">d</div>
<div class="row">e</div>
<div class="row"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/491050.html
標籤:javascript