2017-07-27 41 views
0

所以快速總結:我正在HTML中進行單頁測驗。它有4個單選按鈕和4個標籤。有一個下一步按鈕,用於在單擊測驗時替換問題和答案。我還會在用戶點擊下一步按鈕時記錄用戶的答案。還有一點,但這是我的代碼的主要要點。jQuery選擇器中輸入元素值不起作用的變量

下面是一些示例代碼:

<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中調試它,和警報( prevAns)每次都會返回正確的值。如果我手動執行上面的行,但使用實際的數字而不是變量,例如值='0',在控制檯中該號碼的單選按鈕按計劃進行檢查。所以我不知道什麼是錯的,語法看起來正確嗎?爲什麼它不工作?

+1

嘗試'丙()'代替'ATTR()' – madalinivascu

回答

0

應使用prop代替attr輸入[類型=無線電]:

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

謝謝,我是因爲手動輸入難倒與attr的行仍然工作 – Mark

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

雖然這段代碼可以解決這個問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於改進您的帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 –

+0

@PatrickHund,感謝您的寶貴意見,我將在下一次回答時在帖子中添加解釋。 :) –