簡體   English   中英

JavaScript 在頁面重新加載 [Rails] 時不起作用?

[英]JavaScript does not work on page reload [Rails]?

這是我的 JavaScript:

function showQuestion(id) {
  $(".question").hide();
  $("#"+id).show();
}

$(document).ready(function() {
  current_question=1;
  showQuestion(current_question);
  $("#next_question").click(function(){
    alert('The current question is '+current_question);
    current_question=current_question+1;
    showQuestion(current_question);
  });
  $("#prev_question").click(function(){
    alert('The current question is '+current_question);
    current_question=current_question-1;
    showQuestion(current_question);
  });
});

這是我的show.html.erb [我的 Rails 視圖]:

<div id="questions">
  <% @questions.each_with_index do |q,i| %>
    <div id="<%= i + 1 %>" class="question">
    <strong><%= q.body %></strong>
    <% if q.type == "MultipleChoice" %>
      <% q.choices.each do |choice| %>
        <br /><%= radio_button_tag "question#{q.id.to_s}", "choice#{choice.id}", @answer == choice  %>&nbsp;<%= choice.body %>
      <% end %>
    <% end %>
    <table>
    <tr><td><%= link_to "< Previous", '#', :remote => true, :id => "prev_question" %></td><td><%= link_to "Next >", '#', :remote => true, :id => "next_question" %></td></tr>
    </table>
    </div>
  <% end %>
</div>

因此,當我單擊“下一個”或“上一個”按鈕時,它會起作用。 但在那之后,兩個按鈕都不起作用。 我感覺這與 jQuery 無法正常工作有關。 謝謝!

如果我正確理解了代碼(我不知道 ruby),那么您的 ID 應該是唯一的。 您正在創建許多具有相同 ID 的按鈕。 jQuery 僅附加到第一個(因為應該只有一個)。

嘗試將其更改為 class。 或者(可能更好),從循環中刪除按鈕,只創建一組按鈕。

編輯:另外,雖然這可能不會導致問題,但 ID 不應以數字開頭,除非您使用 HTML5,我認為這可能允許這樣做。

你真的很親近!

問題是您正在為每個具有相同 ID 的問題生成一組鏈接,這是不正確的。 當您第一次單擊其中一個時,聽起來第一組鏈接被隱藏了。

一種解決方案是將帶有“上一個”和“下一個”鏈接的表格移到包含它的標簽之外。 這是一個小提琴,顯示了您的代碼的簡化版本,其中包含問題 div 之外的 prev 和 next 鏈接。 http://jsfiddle.net/QNLF9/

您也可以將鏈接保留在問題 div 中,為其分配 class 並在 jQuery 代碼中使用 class 選擇器。 這是一個例子。 http://jsfiddle.net/traDx/

我希望這會有所幫助。 還有一件小事。 您應該使用 html 轉義碼&lt; &gt; 而不是<>分別。 快樂編碼!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM