jQuery 选择器中输入元素值的变量不起作用
Variable in jQuery selector for input element's value not working
如此简短的总结:我正在 HTML 中进行单页测验。它有 4 个单选按钮和 4 个标签。单击“下一步”按钮会替换我的测验中的问题和答案。每当用户单击“下一步”按钮时,我也会记录他们的回答。还有更多内容,但这是我代码的主要内容。
下面是一些示例代码:
<form name="form1">
<label for="ans0">
<input type="radio" name="answer" id="ans0" value=0>
</label>
<input type="button" id="next" value="Next">
<input type="button" id="back" value="Back">
</form>
function nextClick() {
//jots down answers
answerSheet[currentQuestion] = $("#form1 input[name='answer']:checked").val();
...
currentQuestion++;
populateQA();
...
}
function populateQA() {
//code to replace question and answers from an array
}
function backClick() {
currentQuestion--; // Navigates to the last question
var prevAns = answerSheet[currentQuestion];
alert(prevAns); // my test
$("#form1 input[value=" + prevAns + "]").attr("checked", true);
populateQA();
}
var currentQuestion = 0;
var answerSheet = [];
$("#next").on("click", nextClick);
$("#back").on("click", backClick);
有问题的代码是这样的,在 backClick() 函数中:
$("#form1 input[value=" + prevAns + "]").attr("checked", true);
我尝试在 Chrome 中调试它,并且每次都 alert(prevAns) returns 正确的值。如果我手动执行上面的行但使用实际数字而不是变量,例如value='0',在控制台中,该数字的单选按钮将按计划进行检查。所以我不知道出了什么问题,语法看起来正确吗?为什么它不起作用?
您应该使用 prop
而不是 attr
作为输入 [type=radio]:
$("#selector").prop("checked", true)
$("#form1 input[value='" + prevAns + "']").prop("checked", true);
如此简短的总结:我正在 HTML 中进行单页测验。它有 4 个单选按钮和 4 个标签。单击“下一步”按钮会替换我的测验中的问题和答案。每当用户单击“下一步”按钮时,我也会记录他们的回答。还有更多内容,但这是我代码的主要内容。
下面是一些示例代码:
<form name="form1">
<label for="ans0">
<input type="radio" name="answer" id="ans0" value=0>
</label>
<input type="button" id="next" value="Next">
<input type="button" id="back" value="Back">
</form>
function nextClick() {
//jots down answers
answerSheet[currentQuestion] = $("#form1 input[name='answer']:checked").val();
...
currentQuestion++;
populateQA();
...
}
function populateQA() {
//code to replace question and answers from an array
}
function backClick() {
currentQuestion--; // Navigates to the last question
var prevAns = answerSheet[currentQuestion];
alert(prevAns); // my test
$("#form1 input[value=" + prevAns + "]").attr("checked", true);
populateQA();
}
var currentQuestion = 0;
var answerSheet = [];
$("#next").on("click", nextClick);
$("#back").on("click", backClick);
有问题的代码是这样的,在 backClick() 函数中:
$("#form1 input[value=" + prevAns + "]").attr("checked", true);
我尝试在 Chrome 中调试它,并且每次都 alert(prevAns) returns 正确的值。如果我手动执行上面的行但使用实际数字而不是变量,例如value='0',在控制台中,该数字的单选按钮将按计划进行检查。所以我不知道出了什么问题,语法看起来正确吗?为什么它不起作用?
您应该使用 prop
而不是 attr
作为输入 [type=radio]:
$("#selector").prop("checked", true)
$("#form1 input[value='" + prevAns + "']").prop("checked", true);