如何使用jquery获得域名?
您不需要jQuery,因为简单的javascript就足够了:
alert(document.domain);
实际观看:
console.log("Output;");
console.log(location.hostname);
console.log(document.domain);
alert(window.location.hostname)
console.log("document.URL : "+document.URL);
console.log("document.location.href : "+document.location.href);
console.log("document.location.origin : "+document.location.origin);
console.log("document.location.hostname : "+document.location.hostname);
console.log("document.location.host : "+document.location.host);
console.log("document.location.pathname : "+document.location.pathname);
有关其他与域相关的值,请查看window.location
联机属性。您可能会发现这location.host
是一个更好的选择,因为其内容可能与有所不同document.domain
。例如,URLhttp://192.168.1.80:8080
将仅在中具有ipaddress document.domain
,而在中具有ipaddress和端口号location.host
。
编辑:
如果您不需要支持IE10,则可以简单地使用: document.location.origin
原始答案,如果您需要旧版支持
您可以通过检查定位对象来获得所有这些以及更多信息:
location = {
host: "stackoverflow.com",
hostname: "stackoverflow.com",
href: "http://stackoverflow.com/questions/2300771/jquery-domain-get-url",
pathname: "/questions/2300771/jquery-domain-get-url",
port: "",
protocol: "http:"
}
所以:
location.host
将是域,在这种情况下为stackoverflow.com。对于URL的完整第一部分,可以使用:
location.protocol + "//" + location.host
在这种情况下为http://stackoverflow.com
不需要jQuery。
类似于之前的答案
location.host
全球位置也有关于当前网址的更多有趣信息。(协议,主机,端口,路径名,搜索,哈希)
如果像我一样需要字符串,请使用此功能-确实可以。
function getHost(url)
{
var a = document.createElement('a');
a.href = url;
return a.hostname;
}
但是请注意,如果URL中有一个子域(例如www。),它将返回主机名。相反,如果没有子域,则主机名也不会有一个。
您可以使用以下代码获取当前网址的不同参数
alert("document.URL : "+document.URL);
alert("document.location.href : "+document.location.href);
alert("document.location.origin : "+document.location.origin);
alert("document.location.hostname : "+document.location.hostname);
alert("document.location.host : "+document.location.host);
alert("document.location.pathname : "+document.location.pathname);
不需要jQuery,请使用简单的javascript:
document.domain
document.baseURI
为您提供域+端口。如果图像标签使用相对路径而不是绝对路径,则使用该路径。可能已经解决了,但对其他人可能有用。
var part = location.hostname.split('.');
var subdomains = part.shift();
var upperleveldomains = part.join('.');
二级域名,您可以使用
var sleveldomain = parts.slice(-2).join('.');
检查这个
alert(window.location.hostname);
这将返回主机名称为www.domain.com
//If url is something.domain.com this returns -> domain.com
function getDomain() {
return window.location.hostname.replace(/([a-z]+.)/,"");
}
//If url is something.domain.com this returns -> domain.com
function getDomain() {
return window.location.hostname.replace(/([a-zA-Z0-9]+.)/,"");
}
本文地址:http://javascript.askforanswer.com/jqueryyuhuoquurl.html
文章标签:dns , javascript , jquery
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
文章标签:dns , javascript , jquery
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!