我的AJAX通话不会在下一页上工作,直到我点击刷新

时间:2015-07-26 21:01:53

标签: javascript jquery ajax

我的javascript / ajax可以在我的页面上运行' http://localhost:3000/'但是,当我点击下一页时,它会转到页面' http://localhost:3000/?page=2'它直到我点击刷新按钮然后才能工作。为什么这样,我该如何解决?

编辑*我为下一页添加了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>');
                });
            });
        });
    });
&#13;
&#13;
&#13;

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

3 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

这解决了这个问题。 Turbolinks做的很时髦。

&#13;
&#13;
$(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>' );
                } );
            } );
        } );
    } );
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您很有可能将第2页加载到第1页,然后期望点击链接并重复操作。

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

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

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