11// Quiz interaction functionality with explanations
22document . addEventListener ( "DOMContentLoaded" , ( ) => {
3+ // Mark function to handle quiz answer feedback
4+ const mark = ( li , ok ) => {
5+ li . classList . add ( ok ? "correct" : "incorrect" ) ;
6+ if ( ! li . querySelector ( ".result-label" ) ) {
7+ li . insertAdjacentHTML ( "beforeend" ,
8+ `<span class="result-label">${ ok ? "✔ 正解" : "✖ 不正解" } </span>`
9+ ) ;
10+ const exp = li . dataset . explain || "" ;
11+ if ( exp ) li . insertAdjacentHTML ( "beforeend" ,
12+ `<div class="explain">${ exp } </div>`
13+ ) ;
14+ }
15+ } ;
16+
317 // Initialize all quiz options
418 document . querySelectorAll ( ".quiz-options" ) . forEach ( ( list ) => {
519 list . querySelectorAll ( "li" ) . forEach ( ( li ) => {
@@ -8,38 +22,22 @@ document.addEventListener("DOMContentLoaded", () => {
822 if ( li . classList . contains ( "clicked" ) ) return ;
923
1024 const isCorrect = li . dataset . correct === "true" ;
11- const explanation = li . dataset . explain || "" ;
1225
13- // Add appropriate class based on answer
14- li . classList . add ( isCorrect ? "correct" : "incorrect" ) ;
15- li . classList . add ( "clicked" ) ;
26+ // Mark the clicked answer
27+ mark ( li , isCorrect ) ;
1628
17- // Add explanation if exists
18- if ( explanation ) {
19- const explainEl = document . createElement ( "div" ) ;
20- explainEl . className = "explanation" ;
21- explainEl . textContent = explanation ;
22- li . appendChild ( explainEl ) ;
23- }
24-
25- // Disable further clicks on all options and show explanations
29+ // Mark all other options as disabled
2630 list . querySelectorAll ( "li" ) . forEach ( ( option ) => {
2731 option . style . pointerEvents = "none" ;
2832
2933 // Show correct answer with explanation if user clicked wrong one
30- if ( option . dataset . correct === "true" ) {
31- if ( ! isCorrect ) {
32- option . classList . add ( "correct" ) ;
33- if ( option . dataset . explain ) {
34- const correctExplain = document . createElement ( "div" ) ;
35- correctExplain . className = "explanation" ;
36- correctExplain . textContent = option . dataset . explain ;
37- option . appendChild ( correctExplain ) ;
38- }
39- }
34+ if ( option . dataset . correct === "true" && ! isCorrect ) {
35+ mark ( option , true ) ;
4036 }
4137 } ) ;
42-
38+ } ) ;
39+ } ) ;
40+ } ) ;
4341 // Prevent event bubbling
4442 e . stopPropagation ( ) ;
4543 } ) ;
0 commit comments