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

$(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>

它总是给出“0”,但如果我选择“德里”和“莲花”,它应该给出2的答案。

最佳答案

两件事:
$('[name=q1]').val()将为您提供带有name="q1"的第一个元素的值,而不是选中的元素。为此,添加:checked
你在比较"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/

10-13 04:51