历史记录 api 状态更改函数脚本在每次发生更改时复制函数调用

History api statechange function script duplicates function calls each time change occurs

本文关键字:函数调用 复制 脚本 api 记录 状态 函数 历史      更新时间:2023-09-26

我在一个简单的演示中使用 jquery 历史插件,每次单击导航项时都会加载到特定页面的某个部分中,但我发现每次单击新链接时,History.Adapter.bind(window, 'statechange', function()代码都是重复的。是否可以在每次代码在此函数中完成时解绑它,或者任何人都可以建议我可能出错的地方?

我的测试页面 http://kylehouston.com/_testing/history/page1.html

.JS

navLink.on('click', function(e) {
        e.preventDefault();
        var el = $(this);
        //get the href and remove begining /
        url = el.attr('href')
            .slice(1);
        //do a check to see if this link is already active
        if (el.hasClass('is-active')) {
            return false;
        }
        navLink.removeClass('is-active');
        el.addClass('is-active');

        History.pushState(null, null, url);

        // Bind to StateChange Event
        History.Adapter.bind(window, 'statechange', function() {
            var State = History.getState();
            mainContent.fadeOut(function() {
                $(this)
                    .empty();
                console.log('this ran');
                preloader.fadeIn();
                loadContent(mainContent, location.pathname);
            });
            History.Adapter.unbind();
        });

        //empty mainContent then empty it
        mainContent.fadeOut(function() {
            $(this)
                .empty();
            //display preloader
            preloader.fadeIn();
            //check if content already exists in pages{} if not then make call then save to pages{} or retrieve from pages{} if already exists
            loadContent(mainContent, url);
        });
    });

你有没有试过移动

// Bind to StateChange Event
History.Adapter.bind(window, 'statechange', function() {
    var State = History.getState();
    mainContent.fadeOut(function() {
        $(this).empty();
        console.log('this ran');
        preloader.fadeIn();
        loadContent(mainContent, location.pathname);
    });           
});

以前

navLink.on('click', function(e){