最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to write basic jquery if statement based on url - Stack Overflow

programmeradmin0浏览0评论

I don't know why this doesnt work. Although im sure its something to do with the way im handling the url in the if statement. My Jquery / javascript knowledge if basic.

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

if (url == '.html')
{
  $('#HomeButton').bind('click', HomeButton);
} 

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

doSomething....

};

I don't know why this doesnt work. Although im sure its something to do with the way im handling the url in the if statement. My Jquery / javascript knowledge if basic.

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

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

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

doSomething....

};
Share Improve this question edited Jul 9, 2012 at 7:42 Denys Séguret 383k90 gold badges811 silver badges776 bronze badges asked Jul 9, 2012 at 7:38 mikemike 7492 gold badges13 silver badges24 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

Don't use jquery to access standard object properties.

You can do

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

but you should never pare to the whole URL : you'd have wrong result if you change your domain, test elsewhere, use https, add a parameter, etc. You should use the intended property of location, that is pathname :

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

In case of doubt, if you want to be sure of your pathname, simply open Chrome's developer tools (by typing F12) and type this on the console : document.location.pathname.

window.location isn't a a DOM element so you can't use jQuery methods on it.

The .href is actually a property of a Location object.

Just use it direct - if (window.location.href === ...)

发布评论

评论列表(0)

  1. 暂无评论