我的AJAX调用不能在下一页上工作,直到我点击刷新

My AJAX call won't work on next page untill I hit refresh

本文关键字:刷新 工作 调用 AJAX 不能 一页 我的      更新时间:2023-09-26

我的javascript/ajax工作在我的页面'http://localhost:3000/',但当我点击下一页,它去页面'http://localhost:3000/?page=2'它不工作,直到我点击刷新按钮,然后它将工作。为什么会这样,我该如何解决?

edit*我附加了下一页的haml调用。

    $(function() {
        $('.show_event').click(function(evt) {
            evt.preventDefault();
            console.log("click")
            $.get(this.href,function (code){
                var divs = $(code).filter(function(){
                    return $(this).is('name')
                });
                divs.each(function() {
                    $('.event-text').replaceWith('<div class="event-text">' + $(this).html() + '</div>');
                });
            });
        });
    });

= link_to 'Next page', page: @pages[:page] + 1 unless @pages[:page] >= @pages[:last_page]

试试这个:

$('body').on('click', '.show_event', function(evt) { ...

这解决了这个问题。涡轮链接在做一些古怪的事情。

$(document).ready(ready);
$(document).on('page:load', ready);
function ready() {
    $( function () {
        $( 'body' ).on( 'click', '.show_event', function ( evt ) {
            evt.preventDefault();
            console.log( "click" )
            $.get( this.href, function ( code ) {
                var divs = $( code ).filter( function () {
                    return $( this ).is( 'div#event' )
                } );
                divs.each( function () {
                    $( '.event-text' ).replaceWith( '<div class="event-text">' + $( this ).html() + '</div>' );
                } );
            } );
        } );
    } );
}

最有可能的是你将页面2加载到页面1中,然后期望链接被点击并重复操作。

问题是正在加载的新html没有与事件处理绑定。

您可以使用委托,类似于下面的

 $(document).delegate(".show-event", "click", function () { /* code here */ });