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

前端 未结 4 1725
臣服心动
臣服心动 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: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.

提交回复
热议问题