How do I tell jQuery to run a function on one specific web page only?

前端 未结 4 1726
臣服心动
臣服心动 2021-02-18 21:57

I have some jQuery code that is on every web page of the site (in the head element).

What selector syntax can I use to tell jQuery that a certain function should only ru

相关标签:
4条回答
  • 2021-02-18 22:18

    You could use an if statement checking for top.location.pathname.

    if (top.location.pathname === '/my/path')
    {
        /* magic ... */
    }
    

    Or if you want to make it more portable and give the actual if statement some meaning (so someone reading it will know what it's about) - if you have access to the body element of the document, you can add a class showing that you want to run this script.

    So for instance, if /* magic ... */ in the above example has something to do with including the Facebook API, you could make your body look like <body class="has-facebook-api"> and then make a check with jQuery:

    $(function () // on document.ready()
    {
        if ($('body.has-facebook-api').length > 0)
        {
            /* magic ... */
        }
    });
    

    Make sure this runs after including jQuery inside a separate script tag.


    While we're at it, if you're not using this script to transform the visuals of your page before it gets outputted, I'd advise you to place all or most of your script tags close to your footer to render the page sooner.

    0 讨论(0)
  • 2021-02-18 22:29

    You can't specify the current URL in a jQuery Selector, you can however write a simple check using the document.location object:

    if (document.location.pathname == "/somefolder/somepage") {
       // do some special stuff on this page!
    }
    
    0 讨论(0)
  • 2021-02-18 22:34

    Maybe check window.location.pathname?

    if (window.location.pathname == "/path/to/page.html") {
        callFunction();
    }
    
    0 讨论(0)
  • 2021-02-18 22:35

    I prefer to do stuff like this in whatever language you are writing your app in. Your layout/template/whatever that is serving up your html could simply output a true/false to a javascript variable

    if ($page = '/foo/bar.html/') {
      echo 'baz = true';
    } else {
      echo 'baz = false';
    }
    

    Then have your js check baz to determine whether you should be running these functions or not. You aren't relying 100% on js in this instance, but imo that's better. Your server is going to always know what page/url you are on, and you won't need to worry about browser incompatibilities with your js trying to determine what page it resides on.

    0 讨论(0)
提交回复
热议问题