Targeting window.location.pathname

柔情痞子 提交于 2020-01-15 07:14:38

问题


I have a url similiar to this:

www.mysite.com/products/

I was using this to test against the pathname:

if (/\/products\//.test(window.location)) {
_gaq.push(['_trackPageview', '/products/landing']);
}

But the problem I was running into was the above would execute for sub-folders as well, which I do not want:

www.mysite.com/products/sub-folder/

I'm thinking window.location.pathname will help me out more than the above jQuery. But I'm unsure how to target only the top-level directory, and not the sub directories within it?


回答1:


Add a $ at the end of your regexp:

if (/\/products\/$/.test(window.location)) {
_gaq.push(['_trackPageview', '/products/landing']);
}

example: http://jsfiddle.net/niklasvh/feK4A/




回答2:


window.location.pathname.indexOf("/",1);

so now you can do

var indOf = window.location.pathname.indexOf("/",1);
var myStr = window.location.pathname.substr(0,indOf+1 );

alert( myStr );  // gives you what you want;


来源:https://stackoverflow.com/questions/6392486/targeting-window-location-pathname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!