简体   繁体   中英

Page specific javascript function

I have all my javascript code for i project in a single minified library. There are some functions that run only for specific page urls, but when a link that does not have its href attribute and instead has an element id its href attribute is clicked, and the page is refreshed, the function does not run. Any idea what the problem is? For example; it work when the url is http://localhost/pheedbak/users/home but when the url changes to http://localhost/pheedbak/users/home#directed-pheeds , the function doesn't run

The code is something like this

url = "http://localhost/pheedbak/users/home";

    if(window.location.href == url)
    { 
      pheeds.LoadLatestPheeds();
    }

This should work -- only look at the stuff before #

 if(window.location.href.split("#")[0] == url)

or

 if(window.location.href.split("#",1)[0] == url)

nb. not tested -- might contain typos/bugs.

您可以尝试一下,即使有其他查询字符串或哈希ID,也可以匹配:

if(window.location.href.indexOf(url) > -1)

You'll need to strip out the important part. Eg

var url = 'pheedbak/users/home';

if(window.location.href.replace(/.*?\/\/.*?\/(.*?)(?:\#|\?).*/,'$1') == url)
{ 
  pheeds.LoadLatestPheeds();
}

This will also work with url's that contain GET variables (eg. /users/home?id=2) and works regardless of domain or protocol.

Domain & Protocol dependent version:

var url = 'http://localhost/pheedbak/users/home';

if(window.location.href.replace(/(.*?)(?:\#|\?).*/,'$1') == url)
{ 
  pheeds.LoadLatestPheeds();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM