我不是很确定你为什么这样做,但根据所提供的信息,这里是几行代码是:
- 开始遍历“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