gpt4 book ai didi

javascript - 简单测验不适用于 jQuery 或 JavaScript

转载 作者:行者123 更新时间:2023-11-28 04:29:24 26 4
gpt4 key购买 nike

我正在做一个简单的测验,以获取一个人在提交“提交”按钮时回答的正确问题的数量。但是,它总是给零。请帮助。

$(document).ready(function(){
$('button').click(function(){
var count = 0;
if($('[name=q1]').val() == "Delhi"){count++;}
if($('[name=q2]').val() == "Lotus"){count++;}
alert(count);
});
});
<body> 

<div>
<p>Question: What is capital of India?</p>

<input type="radio" name="q1" value="delhi"> Delhi
<input type="radio" name="q1" value="mumbai"> Mumbai
<input type="radio" name="q1" value="kolkata"> Kolkata
<input type="radio" name="q1" value="lucknow"> Lucknow
</div>

<div>
<p>Question: What is the national flower of India?</p>

<input type="radio" name="q2" value="rose"> Rose
<input type="radio" name="q2" value="lotus"> Lotus
<input type="radio" name="q2" value="sunflower"> Sunflower
<input type="radio" name="q2" value="tulip"> Tulip
</div>

<button>submit</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

</body>

It is always giving '0', but if I select 'Delhi' and 'Lotus' it should give answer as 2.

最佳答案

两件事:

  1. $('[name=q1]').val() 将为您提供带有 name="的第一个元素的值q1",而不是 checked 元素。为此,添加 :checked

  2. 您正在比较 "delhi""Delhi";案件很重要。

$(document).ready(function() {
$('button').click(function() {
var count = 0;
if ($('[name=q1]:checked').val() == "delhi") {
count++;
}
if ($('[name=q2]:checked').val() == "lotus") {
count++;
}
alert(count);
});
});
<div>
<p>Question: What is capital of India?</p>

<input type="radio" name="q1" value="delhi"> Delhi
<input type="radio" name="q1" value="mumbai"> Mumbai
<input type="radio" name="q1" value="kolkata"> Kolkata
<input type="radio" name="q1" value="lucknow"> Lucknow
</div>

<div>
<p>Question: What is the national flower of India?</p>

<input type="radio" name="q2" value="rose"> Rose
<input type="radio" name="q2" value="lotus"> Lotus
<input type="radio" name="q2" value="sunflower"> Sunflower
<input type="radio" name="q2" value="tulip"> Tulip
</div>

<button>submit</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

关于javascript - 简单测验不适用于 jQuery 或 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42269735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com