简体   繁体   中英

Rails, javascript not working when going to next record

In my show page I have a link that takes the user to the next record, when the user clicks on the link, the next pages is loaded but my javascript won't work until I refresh the page

Model

...

def next_question
    self.class.where("id > ?", id).first
end

...

controller

...

def show
    @question = Question.find(params[:id])
end

...

View

...

<div class="row" id="yes_no">
    <div class="col-xs-10 col-md-8 col-xs-offset-1 col-md-offset-2">
        <div id="y_n_buttons">
            <%=link_to yesvote_question_path(@question, yes: true), remote: true, method: :post, id:"yes_button" do%>
                <p>YES</p>
            <% end %><%=link_to yesvote_question_path(@question, yes: false), remote: true, method: :post, id:"no_button" do%>
                <p>NO</p>
            <% end %>
        </div>
    </div>
</div>

<%= link_to("Next", @question.next_question) if @question.next_question %>

Javascript(jquery)

window.onload = function() {
$( "#yes_button" ).click(function() {
  $( "#y_n_buttons" ).slideUp( "slow", function() {
  });
});
$( "#no_button" ).click(function() {
  $( "#y_n_buttons" ).slideUp( "slow", function() {
  });
});

}

when page onload, your buttons bind the click event. However, when you click the next page button and the new loaded DOM would not bind the click event, you need to use on to bind the event, instead of click

window.onload = function() {
$( "#yes_button" ).click(function() {
  $( "#y_n_buttons" ).slideUp( "slow", function() {
  });
});
$( "#no_button" ).click(function() {
  $( "#y_n_buttons" ).slideUp( "slow", function() {
  });
});
}

to

$(function(){
  $(document).on('click', "#yes_button", function() {
    $("#y_n_buttons").slideUp( "slow", function() {
    });
  });
  $(document).on('click', "#no_button", function() {
    $("#y_n_buttons").slideUp( "slow", function() {
    });
  });
})

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