简体   繁体   English

Rails,JavaScript在下一条记录时不起作用

[英]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 在我的显示页面上,我有一个链接,可将用户带到下一条记录,当用户单击该链接时,将加载下一页,但是直到刷新页面后,我的JavaScript才起作用

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) 使用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. 页面加载时,您的按钮会绑定click事件。 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 但是,当您单击下一页按钮并且新加载的DOM不会绑定click事件时,您需要使用on绑定事件,而不是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() {
    });
  });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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