2

所以基本上我只想在 url 看起来像这样的情况下运行代码:www.example.com/#page否则不要像example: www.example.com/whatever/#page, www.example.com/whatever/whatever#pageetc 那样运行 jquery,

我的代码:

$(window).load(function(){
    if(window.location.hash == '#page'){alert('success');}
});

目前它会提醒每个包含#page 的 url。任何建议谢谢!

4

3 回答 3

1

尝试一下

$(window).load(function(){
if(document.location.toString().indexOf('/#page')!=-1){alert('success');}
});
于 2012-08-21T21:14:53.413 回答
0

检查window.location.pathname

if (window.location.pathname == "/sample/sample" && window.location.hash == "#page")

或者对你有用的任何排列

如果您希望根据路径的深度来执行此操作,比如说,仅在路径名至少两深的页面上发出警报,那么您需要拆分路径名

window.location.pathname.split("/").length //this is the depth of the url

所以结合这两个想法并适合你的例子,

var depth = window.location.pathname.split("/").length;
// pathname starts with a /, which adds one to the length of the array, so subtract
depth = depth -1;

// now run our checks
if (depth == 2 && window.location.hash == "#page") alert("success!");
else alert ("failure!");
于 2012-08-21T21:13:04.850 回答
0

怎么样

$(window).load(function(){
    var test = location.protocol + '//' + location.host + '/#page';
    if(test == location){alert('success');}
});
于 2012-08-21T21:24:04.650 回答