简体   繁体   中英

Running Score / Quiz game

I am a beginner coder, and I am working on this quiz-type program. It needs to ask pre-created questions, and then check if you got the right answer, adjust your running score, and then show the next problem. I finished everything else, but the part that is getting me stuck is this part.

 <!doctype html> <html lang="en"> <head> <title>Group Project</title> </head> <body> <script text="text/javascript"> var a = 0; var b = 0; document.write(a, "/", b) function score() { var a = 0; var b = 0; if (document.question.one.value=="10") { ++a; ++b; } else{ ++b; } document.write(a, "/", b) } </script> <form name="question"><br> <input type="text" name="one"/><br> <input type="button" value="Submit" onclick="score()" /> </form> 

I picked 10 in the IF statement just to see is the increment works, but what happens when I do input 10 into the text input, the page reloads, showing only the created fraction and no buttons or text inputs. How can I make it so the score or fraction runs along, and does not need a complete page reload to increment?

In addition to above answer, I would recommend the following. If you are programmatically modifying page contents, you will usually save time by using a library which presents a cleaner/more straight-forward interface. One common library for this purpose is jQuery: http://jquery.com/

You don't want to use document.write as it clears all document to write new content. Instead you should change inner text content of some DOM element, like div . For example:

 <form name="question"> <div id="score"></div> <input type="text" name="one" /> <br> <input type="button" value="Submit" onclick="score()" /> </form> <script text="text/javascript"> var a = 0; var b = 0; write(a, b); function score() { var a = 0; var b = 0; if (document.question.one.value == "10") { ++a; ++b; } else { ++b; } write(a, b); } function write(a, b) { document.getElementById('score').innerHTML = a + "/" + b; } </script> 

In above code I introduced helper function write which displays scope text in the div#score div.

Also note that script now goes after form element, to make sure that write function can locate div#score when it's executed (HTML should be loaded by that time).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM