javascript 在Javascript中从href获取路径名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3807674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:19:10  来源:igfitidea点击:

Get pathname from href in Javascript

javascriptjquery

提问by mike

whats the simplest way to return the "pathname" from an anchor tags href attribute?

从锚标记 href 属性返回“路径名”的最简单方法是什么?

example... say I have:

例如...说我有:

<a href="http://www.example.com/this/is/my/path.html">Blah</a>

I need to return only this "/this/is/my/path.html" part.

我只需要返回这个“/this/is/my/path.html”部分。

Ideas? I'm using jQuery if it helps..

想法?如果有帮助,我正在使用 jQuery。

Thanks!

谢谢!

回答by fehays

I think you can use pathname

我想你可以使用路径名

$('a')[0].pathname;

回答by Aaron Saunders

see working example here.. http://jsfiddle.net/TvNmL/

请参阅此处的工作示例.. http://jsfiddle.net/TvNmL/

HTML..

HTML..

<a id='lnk' href="http://www.example.com/this/is/my/path.html">Blah</a>

javascript...

javascript...

alert( document.getElementById('lnk').pathname);

回答by shem86

I noticed there's still no proper answer that deals with the IE bug that @Funka mentioned, so here's my solution:

我注意到仍然没有正确的答案来处理@Funka 提到的 IE 错误,所以这是我的解决方案:

HTML

HTML

<a href="/foo" id="foo">My link</a>

JS

JS

document.getElementById("foo").getAttribute("href");

results '/foo' on all browsers

结果 '/foo' 在所有浏览器上