我最近更改了我的代码以使其更具响应性,因此弄乱了我的 jQuery 代码以记录小测验的正确与错误答案。当问题位于 HTML 表单标记中时,我在下面发布的 javascript 可以正常工作。既然表单标签不再围绕我的问题,如何修改第二行(声明“answer1”变量的位置)中的 jQuery 代码才能正常工作?非常感谢。
HTML
<div class="intro-header2">
<div class="container">
<h1>The capital of Croatia is ...</h1>
<p> </p>
<div class="radio" style="margin-top: 0px;">
<label><input type="radio" name="capital" value="zagreb" id="zagrebID"> Zagreb</label>
</div>
<div class="radio" style="margin-top: 10px;">
<label><input type="radio" name="capital" value="debrovnik"> Debrovnik</label>
</div>
<div class="radio" style="margin-top: 10px;">
<label><input type="radio" name="capital" value="makarska"> Makarska</label>
</div>
<div class="radio" style="margin-top: 10px;">
<label><input type="radio" name="capital" value="moscow"> Moscow</label>
</div>
<div class="radio" style="margin-top: 20px;">
<input type="button" class="btn btn-info" value=" Next " id="NextID">
</div>
</div> <!--/.container-->
</div> <!--/.intro-header2-->
JS
$("#NextID").click(function(){
var answer1 = ($('input[name=capital]:checked', '#myForm').val());
if (answer1 == "zagreb") {
var QuestionNumber = "Question 1, The capital of Croatia.";
var QuizDesc = "Quiz questions on the country of Croatia.";
var name = localStorage.getItem('name');
var email = localStorage.getItem('email');
//pulls the current counter from local storage
var counter = localStorage.getItem('counter');
//adds one to it
var counter = parseInt(localStorage.getItem('counter')) + 1;
//updates the global variable for counter
setCounter(counter);
passedQues(email, name, QuestionNumber, QuizDesc);
document.location.replace("page3.html");
}
else if (!$("input[name='capital']:checked").val()) {
alert('Nothing is checked!');
return false;
}
else {
var QuestionNumber = "Question 1, The capital of Croatia.";
var QuizDesc = "Quiz questions on the country of Croatia.";
var name = localStorage.getItem('name');
var email = localStorage.getItem('email');
//pulls the current counter from local storage
var counter = localStorage.getItem('counter');
//adds one to it
var counter = parseInt(localStorage.getItem('counter')) + 0;
//updates the global variable for counter
setCounter(counter);
failedQues(email, name, QuestionNumber, QuizDesc);
document.location.replace("page3.html");
}
});
最佳答案
您不再拥有 form
元素,我假设它有一个 id
属性,其值为 myForm
此行在 id 为 myForm
的元素内查找 input
的值
var answer1 = ($('input[name=capital]:checked', '#myForm').val());
该元素不再存在,因此找不到输入值。尝试将此行更改为:
var answer1 = ($('input[name=capital]:checked').val());
关于javascript - 当关键片段 'form'标签不再存在时,如何测试提交的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38726790/