加载标签url内容



这是我的JSFiddle。昨天我发布了关于如何创建标签url的问题。我得到了一个答案,但如果我刷新,它会从初始值开始。

例如:如果我在#content 2上刷新,它会显示#content 1。我不想那样。我想我应该使用加载事件。但不知道如何在这里实现。有什么解决方案吗?请帮帮我。

如果您希望您的选择在页面中被记住,您需要将选择存储在会话/服务器上的某个位置。重新加载页面会从头开始您的脚本,如果您想预选一些内容,则需要从会话中取回数据

另一种选择是使用javascript将选择写入cookie,并读取该cookie以设置初始选择

你可以在这里学习如何使用cookie。该示例使用cookie来存储用户名,但您可以使用它来存储变量"content_selection"。然后,当您的页面加载时,读取cookie值并使用它来选择正确的初始内容。

我已经在使用jquery创建标签url上回答了这个问题。只是在这里分享这一点,因为链接线程最初只是关于用哈希标签(实际上是片段标识符)更新URL,但关于在重新加载后保留内容的相同问题最终由该线程中的OP提出。

对于那些不想额外点击的人来说,代码非常简单。只需在function setActive(i) { // codes }之后添加以下内容:

        var url = window.location.hash; // retrieve current hash value
        if(url.indexOf('Content') != -1){ // do the following if URL's hash contains "Content"
            // remove "#" symbol from retrieved hash value
            var currentHash = window.location.hash.substring(1).split("#");
            // remove "-" symbol from retrieved hash value
            var contentTitle = currentHash.toString().replace(/-/g, ' ');
            // store hash value in "actualContent" variable
            var actualContent = "This is " + contentTitle;
            // remove "selected" for every instance of "myclass" to hide content first
            $(".myclass").removeClass("selected");
            // find div that contains retrieved hash value's text stored in "actualContent" variable and add "selected" class to that div to display the correct content
            $("div:contains('" + actualContent + "')").addClass("selected");
        }

最新更新