I am trying to create a quiz within a website page. The aim is that every time you press next, a new question will open up within the page. However, calling upon the script a second time doesn't work.
To achieve this, I first created a link called 'next'.
<a href="addquiz.html" name="next" id="1">Next</a>
This calls upon a script which opens q1 from addquiz.html
<script>
$("#1").click(function() {
$("#load").load("addquiz.html" + ' #q1');
event.preventDefault();
});
</script>
In this script there is a submit button which calls upon the function goupone, which increases the id of the link by 1 (eg; from 1 to 2)
<div id="q1">
<h3>5 + 19 = ?</h3>
<input type="text" width="6" name="" id="question-1-answers" value="" />
<input type="submit" value="Check" onClick="goupone();" />
</div>
<script>
function goupone(){
var v=document.links[9].id;
vi=parseInt(v);
vi=vi+1;
document.links[9].id=vi;
}
</script>
However, when I click the next button again, nothing happens. Can anyone help?
Since you change the id
from 1
to 2
, the initial click handler $("#1").click()
will no longer be triggered when you click on the anchor. An alternative is to either bind the event handler to an a
whose attribute name
is next
:
<script>
$('a[name="next"]').click(function() {
$("#load").load("addquiz.html" + ' #q1');
event.preventDefault();
});
</script>
Or create a class, say next
, add it to a
, and use it as selector:
<a href="addquiz.html" name="next" id="1" class="next">Next</a>
<script>
$('a.next').click(function() {
$("#load").load("addquiz.html" + ' #q1');
event.preventDefault();
});
</script>
However, I'd refactor your entire code to simply use the following instead:
<a href="addquiz.html" name="next" id="nextAnchor" data-next-id="1">Next</a>
<script>
$("#nextAnchor").on('click', function() {
$("#load").load("addquiz.html#q" + $(this).data("next-id"));
event.preventDefault();
});
</script>
function goupone() {
var $next = $("#nextAnchor");
var currentId = parseInt($next.data("next-id"));
var nextId = currentId + 1;
$next.data("next-id", nextId);
}
Here's a working DEMO .
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.