jQuery代码第一次有效,第二次仅在刷新页面后有效 [英] jQuery code works the first time and the second time works only after page refresh

查看:161
本文介绍了jQuery代码第一次有效,第二次仅在刷新页面后有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jquery代码,可将数据加载到page中.这段代码关于分页的部分在第一次使用时有效,第二次仅在刷新页面后才能使用.

I have a jquery code to load data in page . The part in this code concerning the pagination works at the first time and the second time it doesn't work only after page refresh.

-第一次单击分页中的页面链接时,jquery代码有效并且调用了ajax查询.

-The first time when I click on a link of page in pagination , the jquery code works and th ajax query is called well.

-第二次,当我单击分页页面的链接时,jQuery代码将被忽略,并且分页中的链接就像一个简单的链接一样工作,就好像没有jquery代码一样.

-The seconde time when I click on a link of page of pagination , the jquery code is ignored and the link in the pagination work as a simple link as if there is not a jquery code.

<div id="mydiv">
   {% for entity in entities %}
    //...
   {% endfor %}

{{ knp_pagination_render(entities) }}

</div>


    <script>
    $(document).ready(function () {

        $("ul#pagination a").on('click', function (e) {
            e.preventDefault();

            $('ul#pagination li.active').removeClass("active");

            var route = $(this).attr('href');

            window.history.pushState(null, "Title", route);

            return loadPage(route);

        });

        function loadPage(route) {
            $.ajax({
                type: 'get',
                dataType: 'html',
                url: route,
                success: function (msg) {
                    if (msg === undefined) {
                        alert('error');
                    }
                    else {
                        $('#mydiv').html(msg);
                    }
                }
            });

        }

        window.onpopstate = function () {
            loadPage(window.location.href);
        };

        });
</script>

推荐答案

如上所述,这是因为您正在动态加载内容.您的活动尚未绑定到此内容.

As mentioned, it's because you're dynamically loading the content; your event is not bound to this content yet.

尝试更改

$("ul#pagination a").on('click', function (e) {

$(document).on('click', "ul#pagination a", function (e) {

这会将事件绑定到动态创建的元素.

This binds the event to dynamically created elements.

这篇关于jQuery代码第一次有效,第二次仅在刷新页面后有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆