简体   繁体   中英

Javascript not working after rendering partial rails

<% if @questions_counter == 2 %>
  <% if @finish_btn == 0 %>
    $("#initial-question-frame").fadeOut('fast');
    $("#next-question-frame").html("<%= escape_javascript(render(:partial => "question", :locals => {:question => @question})) %>").fadeIn();
  <% else %>
    $("#initial-question-frame").fadeOut('fast');
    $("#next-question-frame").html("<%= escape_javascript(render(:partial => "question", :locals => {:question => @question})) %>").fadeIn();
    $("#process-question-submit").fadeOut();
    $("#finish-test-button").fadeIn();
  <% end %>

The problem is, when @finish_btn = 1 ,

#process-question-submit is not fading out, nor the #finish-test-button fades in

Note: that both buttons are inside the rendered partial above.

This is because, render a partial just insert the HTML to the view before javascript run by the browser. In that case, DOM event handler goes to inactive.

To resolved this, just bind your DOM inside the document and it will keep your handler still active even after ajax call.

<% if @questions_counter == 2 %>
  <% if @finish_btn == 0 %>
    $("#initial-question-frame").fadeOut('fast');
    $("#next-question-frame").html("<%= escape_javascript(render(:partial => "question", :locals => {:question => @question})) %>").fadeIn();
  <% else %>
    $("#initial-question-frame").fadeOut('fast');
    $("#next-question-frame").html("<%= escape_javascript(render(:partial => "question", :locals => {:question => @question})) %>").fadeIn();

    $(document).ready(function() {
      $("#process-question-submit").fadeOut();
      $("#finish-test-button").fadeIn();
    });
  <% end %>
<% end %>

Have you tried this?

var _question = "<%= j render(:partial => 'question', :locals => {:question => @question}) %>";
$('#next-question-frame').empty();
$('#next-question-frame').append(_question);
$("#process-question-submit").fadeOut();
$("#finish-test-button").fadeIn();

Your Javascript should work, so it seems the partial might not be rendering properly. If this doesn't work, you might try troubleshooting by just getting the partial to show first with #finish-test-button {display: block;} to make sure it's showing up.

If none of that works, try putting the Javascript to fade in the button inside the partial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM