我猜我需要为此制作一个 cookie,但是请告诉我是否还有其他方法。我有一个下拉菜单,它使用链接元素来选择网站上的语言,根据他们选择的链接元素,创建一个哈希值并附加到 URL 的末尾。我正在寻找一种方法来存储此选择,以便该选择保留在所有页面上,而不是在每次刷新或离开页面时重置。
这是 HTML:
<div class="menu cid">
<a href="#" title="en">United States</a>
<a href="#" title="can">Canada</a>
</div>
脚本:
$(document).ready(function(){
if(document.location.hash == ""){
location.href = location.href + "#en";
}
});
jQuery('.menu a').on('click', function(event) {
event.preventDefault();
var clickedAnchor = jQuery(this),
countryID = clickedAnchor.attr('title');
location.href = location.href.split('#')[0] + '#' + countryID;
location.reload();
});
var countryID = window.location.hash;
countryID = countryID.substring(1);
console.log("country code: "+countryID);
var countryID = "en";
if (document.location.hash != "") {
countryID = document.location.hash.substring(1);
}
var map = {"en":"4242", "can":"4243"};
cii_EmbedProductLinks('Chairs','{{ prodID }}',map[countryID], CI_LinkID);
谢谢!
最佳答案
可能的解决方案是,
- cookie - 如果您需要客户端实现,请注意过期时间
- html5 Web 存储(本地存储、 session 存储) - 仅客户端,如果您没有不使用 html5 的限制。我认为 session 存储更适合您的情况,因为它将保留设置直到用户 session 过期。
- 服务器 session - 如果您要根据所选值(即语言)提供内容,则此方式更适合。这通常用于支持 i18n 的系统,这些系统需要随时了解服务器端和客户端选择的语言。
关于javascript - 存储哈希信息以供下拉选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19663929/