在線考試系統中,根據題目類型 (單選、多選、填空、問答等) 執行不同的答案保存、計分、統計邏輯。
switch (objNameType) {
case 'PD': // 判斷題
case 'DANX': // 單選題
case 'PP': // 匹配題
// 相似邏輯:獲取 ID、加載用戶答案、統計未答題數
break;
case 'text': // 填空題
case 'textarea': // 問答題
// 文本值處理、空值清理、答題數增減
break;
case 'checkbox': // 多選題
// 複雜:值拼接、部分選中、全清空邏輯
break;
default:
return;
}
class AnswerHandler {
constructor(exam, userData, stats) {
this.exam = exam;
this.userData = userData;
this.stats = stats; // qNoTotalD, qIdNoStr 等統計對象
}
handle(obj) { throw new Error('Must implement'); }
// 共用工具方法
getTempGroupId(obj) {
return obj.id.substr(0, obj.id.indexOf('_'));
}
incrementStat(obj) {
const tgId = this.getTempGroupId(obj);
this.stats.qNoTotalD[this.stats.qIdNoStr[tgId]]++;
}
decrementStat(obj) {
const tgId = this.getTempGroupId(obj);
this.stats.qNoTotalD[this.stats.qIdNoStr[tgId]]--;
}
}
// 選擇類題型基類
class ChoiceHandler extends AnswerHandler {
handle(obj) {
const id = obj.id;
const loadVUD = this.userData.load(this.exam, id);
if (!loadVUD) this.incrementStat(obj);
}
}
// 文本類題型
class TextHandler extends AnswerHandler {
handle(obj) {
const id = `text_${obj.id}`;
const value = obj.value;
const loadVUD = this.userData.load(this.exam, id);
if (!loadVUD) {
if (value) this.incrementStat(obj);
} else {
if (!value) {
this.userData.remove(this.exam, id);
this.decrementStat(obj);
}
}
}
}
// 多選題型
class CheckboxHandler extends AnswerHandler {
handle(obj) {
const key = `checkbox_${obj.id.substr(0, obj.id.lastIndexOf('_'))}`;
let valueUD = this.userData.load(this.exam, key);
const checked = obj.checked;
if (!valueUD) {
if (checked) {
this.userData.save(this.exam, key, obj.id);
this.incrementStat(obj);
}
} else {
const values = valueUD.split(',');
const idx = values.indexOf(obj.id);
if (checked && idx === -1) {
values.push(obj.id);
this.userData.save(this.exam, key, values.join(','));
} else if (!checked && idx !== -1) {
values.splice(idx, 1);
if (values.length) {
this.userData.save(this.exam, key, values.join(','));
} else {
this.userData.remove(this.exam, key);
this.decrementStat(obj);
}
}
}
}
}
const handlerMap = {
'PD': new ChoiceHandler(exam, UserData, stats),
'DANX': new ChoiceHandler(exam, UserData, stats),
'PP': new ChoiceHandler(exam, UserData, stats),
'text': new TextHandler(exam, UserData, stats),
'textarea': new TextHandler(exam, UserData, stats),
'checkbox': new CheckboxHandler(exam, UserData, stats)
};
function processAnswer(obj, objNameType) {
const handler = handlerMap[objNameType];
if (handler) handler.handle(obj);
}
若邏輯較簡單,可用對象映射替代類:
const handlers = {
'PD': (obj) => handleChoice(obj, 'id'),
'DANX': (obj) => handleChoice(obj, 'name'),
'text': (obj) => handleText(obj, 'text_'),
'checkbox': handleCheckbox
// ...
};
handlers[objNameType]?.(obj);