以下if語句在timeupdate
事件中使用,所以它被稱爲每秒3-4次。雖然這種方法工作得很好,但我覺得它沒有吸引力,我希望得到一些提示,讓它成爲一個更簡單的解決方案,而不會重複。如何使聲明不重複?
if (percent_watched >= 100) {
while (i === 10) {
console.log('video ended');
i++;
// Ajax Request
}
} else if (percent_watched >= 90) {
while (i === 9) {
console.log('90% watched');
i++;
// Ajax Request
}
} else if (percent_watched >= 80) {
while (i === 8) {
console.log('80% watched');
i++;
// Ajax Request
}
} else if (percent_watched >= 70) {
while (i === 7) {
console.log('70% watched');
i++;
// Ajax Request
}
} else if (percent_watched >= 60) {
while (i === 6) {
console.log('60% watched');
i++;
// Ajax Request
}
} else if (percent_watched >= 50) {
while (i === 5) {
console.log('50% watched');
i++;
// Ajax Request
}
} else if (percent_watched >= 40) {
while (i === 4) {
console.log('40% watched');
i++;
// Ajax Request
}
} else if (percent_watched >= 30) {
while (i === 3) {
console.log('30% watched');
i++;
// Ajax Request
}
} else if (percent_watched >= 20) {
while (i === 2) {
console.log('20% watched');
i++;
// Ajax Request
}
} else if (percent_watched >= 10) {
while (i === 1) {
console.log('10% watched');
i++;
// Ajax Request
}
}
感謝您的分享知識:-)
您是否聽說過switch語句? – user45681
我從來沒有使用過它,因爲我對JavaScript相當陌生,但我一定會採取這種解決方案。 –
你使用'while'循環肯定是奇怪的。循環體總是最多執行一次(因爲你正在修改體內的「i」)。我建議閱讀JavaScript教程以更好地理解基本構造:http://eloquentjavascript.net/02_program_structure.html。 –