我不是很確定你爲什麼這樣做,但根據所提供的信息,這裏是幾行代碼是:
- 開始遍歷「thingArray」和增量「loopCount」變種
- 當「loopCount」等於2,我們跳出循環並綁定click事件
- 當點擊事件已觸發TWIC e,我們稱之爲「簡歷」功能,循環使用剩餘的項目。
變量loopCount並不是必需的,但是我已經把它放在那裏,以便您可以參考它來創建在此過程中發生的其他邏輯。你顯然可以使用循環內的本地i var來進行簡單的增量檢查。
'break'語句是這裏的關鍵組件,代碼主要是爲了證明這一點。
小提琴:https://jsfiddle.net/jbird/2zza826j/
在瀏覽器控制檯,你會看到一條消息,每次點擊的事件,最後,當循環中的「恢復」功能完成後,您會看到整數4這是長的陣列顯然。
哦,我不會建議直接在窗口上綁定用戶啓動的事件。
var clickTarget = document.querySelectorAll('.click-target')[0],
loopCount = 0,
clickCount = 0,
thingArray = ['thing1', 'thing2', 'thing3', 'thing4'],
thingDoneArray = [];
function start() {
for (var i = 0; i < thingArray.length; i++) {
loopCount += 1;
thingDoneArray.push(thingArray[i])
if(loopCount == 2) {
// Bind your click event
clickTarget.addEventListener('click', onClick);
// Alert the user
alert('Click the page twice...for some reason.');
// Break out of the loop (this is the important part)
break;
}
}
}
function resume() {
for(var i = 0; i < thingArray.length - thingDoneArray.length; i++) {
loopCount += 1;
}
console.log(loopCount);
}
function onClick(evt) {
evt.preventDefault();
clickCount += 1;
console.log('1 click event happened.');
if(clickCount == 2) {
clickTarget.removeEventListener('click', onClick);
resume();
}
}
start();
我想你應該提供更多的上下文。你爲什麼做這個?爲什麼不只是聽取2個點擊事件,然後在發生時進行循環播放? – Jbird
如果目標是循環遍歷2個部分的數組,然後使用Array.protototype.slice()創建兩個數組。 – Jbird