如何重置会话存储在除一个链接外的每个链接上单击

How to reset sessionStorage on every link click except one?

本文关键字:链接 何重置 单击 一个 存储 会话      更新时间:2023-09-26

我遇到了使用无限滚动并将用户返回到其先前位置的问题。我将用户的滚动位置和通过AJAX加载的帖子内容存储在sessionStorage中。问题是,如果他点击了除帖子页面链接之外的任何按钮/链接,我想重置这个会话。所以我有这个

    $("a").on( "click", function(e) {
        e.preventDefault();
        $(".refresh").attr("is-refresh", "false");
        //If user doesn't click on a post link we will reset storage to its default.
        if($(this).hasClass('post-page')) {
            sessionStorage.setItem("scroll_position", $(window).scrollTop());
            window.location = $(this).attr('href');
        } else {
            sessionStorage.removeItem("posts_to_append");
            sessionStorage.removeItem("pagination_to_append");
            window.location = $(this).attr('href');
        }
    });

问题是,如果用户单击刷新页面按钮,这并没有帮助。我想了很多,没能想出一个简单的解决办法。

如果有帮助的话,这里是我的要点,代码可以进行整个无限滚动,包括保持用户的位置。我只需要通过刷新按钮识别页面刷新。https://gist.github.com/itzikbenh/5cc5fb05b393a1516af70bc0fde3fa18

您缺少的是$(function () {})sessionStorage.removeItem

给,试试这个。

$(function () { 
    // code inside this function will execute on every page refresh afer the DOM is ready
    clearScrollPosition();
    $('a').on('click', function(e) {
        if ($(this).hasClass('post-page') == false) 
            clearScrollPosition();
    });
    function clearScrollPosition() {
        // clear a session storage item
        sessionStorage.removeItem('scroll_position');
    }
});