![](/img/trans.png)
[英]How to create an onclick cookie link and then after navigating to link's url, have that cookie redirect the current url
[英]How to create a link that will keep the current url path
大家好,我需要帮助。 在网站上,我必须到达美国和澳大利亚。 我希望人们能够在商店之间切换而不会失去他们的位置(面包屑)
假设他们在这里:
mydomain.com/us/category/item/
我想要一个链接,它将带您到整个网站上不同位置的相同路径:
mydomain.com/au/category/item/
所以我需要一些如何创建AU链接,将您带到那里
[mydomain.com]/[change this]/[keep same]
使用javascript并替换
$(document).ready(function() {
$('#UStoUK').click(function() {
var url = 'mydomain.com/us/category/item/'
url = url.replace('/us','/uk')
window.location.href = url;
});
});
虽然pshyoulost的答案有效,但我认为您应该更安全一些:
var formatLinkForOtherCountry = function (destination) {
// return if you want to use this link else
// otherwise, just do `window.location.href = window.location.href.replace...`
return window.location.href.replace(/(.+\.com\/)(.{2})/, "$1" + destination);
}
仅使用url.replace('/us','/uk')
可能意味着像yourdomain.com/us/category/items/someWordStartingWithUs/...
这样的链接将转换为yourdomain.com/uk/category/items/ukmeWordStartingWithUs/...
,将无法正常工作。 相反,您可以使用正则表达式:
/ # start regex
( # open capturing group 1 ($1)
.+\.com\/ # all characters until ".com"
) # close capturing group 1
( # open capturing group 2
.{2} # continue for two characters
) # end capturing group 2
/ # end regex
然后,在String.prototype.replace
函数中,我们可以将匹配的所有实例(两个捕获组)替换为"$1" + destination"
。
您可以使用split
和replace:
function changeDir (i, s) {
var url = location.pathname.split('/');
url[i] = s;
window.location.href = url.join('/');
}
要使用此功能,请执行以下操作:
changeDir(URL Part, New Value);
一个例子是:
changeDir(1, 'uk');
确定URL部分 。 一个解释是:
example.com/us/category/item
⬆ ⬆ ⬆
Part: 1 2 3
随意将其添加到location
对象(我不知道这是否是不好的做法。)
window.location.change = function (i,s) {
var url = location.pathname.split('/');
url[i] = s;
window.location.href = url.join('/');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.