我有单选按钮,我想在每个正确答案的最后计算显示分数。在下面的代码表中是数据库表,choice1,choice2,choice3,answer都是选项。我想最后显示总问题的总分。下面是我的javascript,每次点击下一个按钮时,js中的总和值都会重置。单击每个按钮后如何保存sum变量。 谢谢
Twig文件
{% set counter = 0 %}
{% for table in entities %}
<form role="form">
<div class="checkbox">
<label><input type="radio"name="choices" >{{ table.choice1 }}</label>
</div>
<div class="checkbox">
<label><input type="radio" name="choices">{{ table.choice2 }}</label>
</div>
<div class="checkbox">
<label><input type="radio" name="choices">{{ table.choice3 }}</label>
</div>
<div class="checkbox">
<label><input type="radio"name="choices" >{{ table.answer }}</label>
</div>
{% if counter==entitites|length %}
<button onclick="submitanswer()" >Submit</button>
{% else %}
<li> <a onclick="myFunction()" href="{{ path('view', route_params | merge({ 'id': table.Id+1 })) }}">Next</a></li>
{% endif %}
</form>
{% endif %}
{% set counter = counter+1 %}
{% endfor %}
的Javascript
{% block javascript %}
<script>
var choice, choices;
var sum = 0;
function myFunction() {
choices=document.getElementsByName("choices");
for(var i = 0; i < choices.length; i++){
if(choices[i].checked){
choice = choices[i].value;
}
}
alert(choice);
alert(choices[3].value);
if(choice==choices[3].value){
sum += 1;
alert(sum);
}
else{
alert(sum);
}
{#if(choice=={{ answer }}){#}
{##}
{#}#}
{#alert({{ entities[0].answer }});#}
{#return sum;#}
}
function submitanswer(){
choices=document.getElementsByName("choices");
for(var i = 0; i < choices.length; i++){
if(choices[i].checked){
choice = choices[i].value;
}
}
if(choice==choices[3].value){
sum += 1;
}
alert(sum);
}
</script>
{% endblock %}