本文介绍了在javascript中创建一个新的Location对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在javascript中创建新的Location对象?我有一个url作为字符串,我想利用javascript已经提供的内容来访问它的不同部分。
Is it possible to create a new Location object in javascript? I have a url as a string and I would like to leverage what javascript already provides to gain access to the different parts of it.
这是我的一个例子谈论(我知道这不起作用):
Here's an example of what I'm talking about (I know this doesn't work):
var url = new window.location("http://www.example.com/some/path?name=value#anchor");
var protocol = url.protocol;
var hash = url.hash;
// etc etc
这样的事情是可能的,还是我必须要创建这个对象我自己?
Is anything like this possible or would I essentially have to create this object myself?
推荐答案
好吧,您可以使用锚元素来提取网址部分,例如:
Well, you could use an anchor element to extract the url parts, for example:
var url = document.createElement('a');
url.href = "http://www.example.com/some/path?name=value#anchor";
var protocol = url.protocol;
var hash = url.hash;
alert('protocol: ' + protocol);
alert('hash: ' + hash);
它适用于所有现代浏览器,甚至适用于IE 5.5 +。
It works on all modern browsers and even on IE 5.5+.
查看示例。
这篇关于在javascript中创建一个新的Location对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!