求可在Chrome控制台运行的自动选中指定单选按钮脚本
嘿,我太懂你每天重复点单选按钮的痛苦了——这种机械任务完全应该交给脚本搞定!结合你只有少量HTML知识的情况,我给你准备了几个简单易上手的Chrome控制台脚本,复制粘贴就能用,还能灵活调整选择规则:
一、基础版:所有题目统一选固定位置的选项
如果大部分题目都选同一个位置的选项(比如第2个、最后一个),用这个脚本最方便:
// 第一步:把页面上所有单选按钮按题目分组(同一个题的单选按钮会共享name属性) const radioGroups = Array.from(document.querySelectorAll('input[type="radio"]')) .reduce((groups, radio) => { const groupName = radio.name; if (!groups[groupName]) groups[groupName] = []; groups[groupName].push(radio); return groups; }, {}); // 第二步:设置你要选的选项位置(注意:索引从0开始!第1个选项写0,第2个写1,最后一个写group.length - 1) const targetIndex = 1; // 这里示例选第2个选项,你可以按需修改 // 第三步:自动选中每个题的目标选项,并触发页面识别事件(避免部分网站不响应) Object.values(radioGroups).forEach(group => { if (group[targetIndex]) { group[targetIndex].checked = true; group[targetIndex].dispatchEvent(new Event('change')); } });
怎么用:
- 打开Chrome开发者工具:按
F12,或者右键页面→「检查」 - 切换到「Console」标签页
- 复制上面的代码,修改
targetIndex的值(比如要选最后一个选项,就改成group.length - 1) - 按回车执行即可
二、进阶版:自定义每道题的选择(不同题选不同选项)
如果有部分题目需要选不同的选项,比如第1题选第3个,第5题选最后一个,用这个脚本可以精准控制:
// 第一步:按页面顺序获取所有单选按钮组 const radioGroups = Array.from(document.querySelectorAll('input[type="radio"]')) .reduce((groups, radio) => { const groupName = radio.name; if (!groups[groupName]) groups[groupName] = []; groups[groupName].push(radio); return groups; }, {}); const orderedGroups = Array.from(Object.values(radioGroups)); // 确保顺序和页面题目一致 // 第二步:定义每道题的选择规则(数组长度要和你的题目数一致,这里是18个元素) // 规则:0=第1个选项,1=第2个,...,-1=最后一个选项 const optionsToSelect = [2, 0, -1, 1, 3, 0, -1, 2, 1, 0, 3, -1, 2, 1, 0, 3, -1, 2]; // 第三步:逐个设置选中状态 orderedGroups.forEach((group, index) => { const targetIndex = optionsToSelect[index]; const actualIndex = targetIndex === -1 ? group.length - 1 : targetIndex; if (group[actualIndex]) { group[actualIndex].checked = true; group[actualIndex].dispatchEvent(new Event('change')); } else { console.log(`第${index+1}题找不到第${actualIndex+1}个选项,已跳过`); } });
重点修改:
你只需要调整optionsToSelect数组里的数字就行,每个位置对应一道题的选择,比如第1个元素对应页面第1题,写2就是选第3个选项,写-1就是选最后一个。
三、适配特定页面结构的版本(可选)
如果你的页面每个题目都在固定的容器里(比如带question-item类的div),可以用更精准的选择方式,避免干扰其他元素:
// 获取所有题目容器 const questionContainers = document.querySelectorAll('.question-item'); // 同样定义每道题的选择规则 const optionsToSelect = [1, 0, -1, ...]; // 补全18个元素 questionContainers.forEach((container, index) => { const radios = container.querySelectorAll('input[type="radio"]'); const targetIndex = optionsToSelect[index]; const actualIndex = targetIndex === -1 ? radios.length - 1 : targetIndex; if (radios[actualIndex]) { radios[actualIndex].checked = true; radios[actualIndex].dispatchEvent(new Event('change')); } });
小提醒
- 如果脚本没反应,右键单选按钮→「检查」,看看它的HTML结构有没有特殊class或属性,把代码里的选择器(比如
input[type="radio"])改成对应的(比如.radio-btn)就行 - 执行前记得刷新页面,确保所有题目都加载完成
- 控制台如果报错,不用慌,错误提示会告诉你哪里有问题(比如某个题的选项数量不够)
内容的提问来源于stack exchange,提问作者Dagobert
相关产品推荐
相关产品推荐

