Google Slides Apps Script弹窗循环异常问题求助
问题根源
原代码的核心问题是:进入循环后,result变量未被重新更新。用户第一次点击YES进入循环后,后续弹窗的点击结果没有赋值给result,导致循环始终认为用户选择的是YES,会一直执行到count达到8才停止。
修复后的代码
function onOpen() { showAlert(); } function showAlert() { var ui = SlidesApp.getUi(); var messages = [ 'SELF-ASSESSMENT: Be sure to complete the self-assessment before you commence work on this topic.', 'BASIC PRESENTATION: Record your full name, title (for the slide), date and WALT onto all work slides', 'CONTENT: Use a combination of text (your own words) and images for higher marks.', 'EVIDENCE: There are 3 assessment objectives for each topic. Be sure to use at least 3 slides of work when presenting your evidence. One slide for each objective.', 'SOURCES: Whenever you use an image, or refer to text that you found (elsewhere) relevant to the topic. Be sure to reference it, by adding a link to the source place holders.', 'COLLABORATE: Use the SHARE tool, to share your topic journal with a work buddy. Be sure to set the permissions to VIEW. Have your work buddy do the same, and then check in on each others work, give each other feedback and keep the support going.', 'SUPPORT: Use the support site/resource called CADD. There is a link to the support on Google Classroom', 'HAND IN: Dont forget to click the HAND IN button on the assignment, before the due date!' ]; var seenMessages = []; var today = new Date(); var dateString = today.toLocaleDateString(); var result = ui.alert( 'Welcome to your computing journal. Today is ' + dateString + '. Would you like to see some helpful reminders, that might help you maximise your marks?', 'Do you want another reminder?', ui.ButtonSet.YES_NO); if (result == ui.Button.NO || result == ui.Button.X) { ui.alert('That\'s all for now, time to get on with your work!', 'OK', ui.ButtonSet.OK); } else { // 循环条件改为未展示的消息数量小于总消息数,适配数组长度变化 while (seenMessages.length < messages.length) { var randomIndex = Math.floor(Math.random() * messages.length); var message = messages[randomIndex]; if (!seenMessages.includes(message)) { seenMessages.push(message); // 每次弹窗后更新用户选择的结果 result = ui.alert(message, 'Do you want another reminder?', ui.ButtonSet.YES_NO); // 检测到用户选择NO或关闭,立即终止循环 if (result == ui.Button.NO || result == ui.Button.X) { ui.alert('That\'s all for now, time to get on with your work!', 'OK', ui.ButtonSet.OK); break; } } } // 所有提醒展示完毕后的提示 if (seenMessages.length === messages.length) { ui.alert('All reminders have been shown!', 'OK', ui.ButtonSet.OK); } } }
关键修改点
- 更新用户选择结果:每次调用
ui.alert后,将返回值重新赋值给result,让循环能感知用户的最新操作 - 新增循环终止逻辑:每次获取新的
result后,立即判断是否为NO/X,若是则执行提示并通过break跳出循环 - 优化循环条件:用
seenMessages.length < messages.length代替固定的count < 8,后续修改提醒数组长度时无需调整循环条件 - 补充全量展示反馈:当所有提醒都展示完毕时,给用户明确的结束提示
内容的提问来源于stack exchange,提问作者James Greenwood
相关产品推荐
相关产品推荐

