在网址中获取带有英镑符号的window.location.pathname-javascript [英] Fetching the window.location.pathname with a Pound Sign in the URL - javascript
问题描述
在我的网页上,我隐藏并显示了一些文章列表,具体取决于用户点击的链接
On my webpage I have a list of articles that I hide and show depending on which link a user clicks
<a id="sports" href="#">Sports</a>
<a id="weather" href="#">Weather</a>
当我在URL上附加文章id
的方式将某人链接到我的网站时,我想在同一<a>
元素上触发点击事件
When I link a person to my site with the id
of the article appended to the URL, I want to fire a click event on that same <a>
element
例如,如果共享的URL是
For example, if the URL shared is
http://mywebpage.com/page-1/#/weather
页面加载后应触发此事件,如下所示:
This event should be fired after the page loads, something like this:
if(linkInUrl === 'weather') $("a#weather").trigger("click");
所以我的问题是,如何获得linkInUrl
?我知道window.location.pathname
将在.com之后获取路径,但它不会获取/#/
之后的内容.有什么想法吗?
So my question is, how can I get linkInUrl
? I know window.location.pathname
will get the path after the .com, but it doesn't fetch whatever is after the /#/
. Any thoughts?
推荐答案
您可以使用window.location.hash
来检索URL中的值.然后,您只需要删除/
,然后可以通过该ID选择元素并在其上引发click事件:
You can use window.location.hash
to retrieve the value in the URL. You simply then need to remove the /
and you can select the element by that id and raise a click event on it:
if (window.location.hash) {
var target = window.location.hash.replace('/', '');
$('#' + target).trigger('click');
}
这篇关于在网址中获取带有英镑符号的window.location.pathname-javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!