是否有一种使用普通HTML链接到顶级域(TLD)的方法?
<a href="{magic}/">Go to TLD</a>想象一下我在http://subdomain.example.com/subfolder上。现在,我要跳到根文件夹所要做的就是使用/作为href属性-好的。
但是如果我想跳到http://example.com而不是http://subdomain.example.com呢?
甚至更好:
从http://subdomain.example.com/subfolder到http://example.com/subfolder (相同的子文件夹)?
当然,我可以在JavaScript中这样做:
var urlParts = location.hostname.split('.');
var tld = urlParts.slice(-2).join('.');
var a = document.createElement('a');
a.href = '//' + tld;
a.innerHTML = "Go to TLD";
var a2 = document.createElement('a');
a2.href = '//' + tld + window.location.pathname;
a2.innerHTML = "Go to same folder on TLD";
document.body.appendChild(a);
document.body.appendChild(a2);
但难道没有别的办法吗?
发布于 2016-01-15 17:14:04
到目前为止,如果不解析URL并将其输出,这是不可能的。没有类似于../的标准(上一个文件夹)允许“跳上”一个域级别。对于不同的基于JS的解决方案,您可以选择一种更简单的regex方法,但是检查是否可以上升一个级别是很棘手的(例如。example.co.uk会变成co.uk)。尽管如此,下面是regex方法:
var hostname = 'test.example.com'; //location.hostname
var tld = hostname.replace(/^.*\.([^.]+\.[^.]+)$/,'$1');
document.write(tld);
https://stackoverflow.com/questions/34816207
复制相似问题