jQuery选择器中的变量,用于输入元素的值不起作用

时间:2017-07-27 08:43:24

标签: javascript jquery selector

如此快速的总结:我正在用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)每次都返回正确的值。如果我手动执行上述行但是使用实际数字而不是变量,例如value ='0',在控制台中,按照计划检查该号码的单选按钮。所以我不知道什么是错的,语法看起来不错?为什么它不起作用?

2 个答案:

答案 0 :(得分:0)

您应该使用prop代替attr来输入[type = radio]:

$("#selector").prop("checked", true)

答案 1 :(得分:-1)

$("#form1 input[value='" + prevAns + "']").prop("checked", true);