如何基于url编写基本的jquery if语句

时间:2012-07-09 07:38:19

标签: javascript jquery

我不知道为什么这不起作用。虽然我确定它与我在if语句中处理url的方式有关。我的Jquery / javascript知识,如果基本的话。

var url = $(location).attr('href');

if (url == 'http://www.website.com/test/index.html')
{
  $('#HomeButton').bind('click', HomeButton);
} 

function HomeButton(e) {
e.preventDefault();

doSomething....

};

2 个答案:

答案 0 :(得分:3)

不要使用jquery来访问标准对象属性。

你可以做到

if (document.location.href == 'http://www.website.com/test/index.html')

但是你永远不应该与整个网址进行比较:如果您更改域名,在其他地方进行测试,使用https,添加参数等,您的结果会有错误。您应该使用location的预期属性,那是pathname

if (document.location.pathname == '/test/index.html')

如有疑问,如果您想确定自己的路径名,只需打开Chrome的开发者工具(输入F12),然后在控制台上输入:document.location.pathname

答案 1 :(得分:1)

window.location不是DOM元素,因此您不能在其上使用jQuery方法。

.href实际上是Location对象的属性

直接使用它 - if (window.location.href === ...)