简体   繁体   中英

Jquery consistent title header text across all pages

I have a jquery mobile site - a one-pager - and I'm having trouble with the text in the header. It's a simple site with only 5 pages that are all divs with data-role=page. When the page loads I use $.get to retrieve a JSON formatted array generated by an external PHP page. The process page uses a url variable to determine which data to retrieve from our db:

$.get("ajax/siteInfo.php?id=" + getURLvar( 'id' ), function(siteData){
  sessionStorage.siteTitle = siteData.siteTitle;
}, "json");

There's more data than the 1 item but I'm shortening it for simplicity. The JSON array is retrieved successfully and I can see all of the data key-value pairs in my console.

Also want to point out that I have a function that returns the url var when the site page is loaded (/index.html?id=2001):

function getURLvar( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

Now, I want to use sessionStorage.siteTitle in each of the 5 pages:

<div data-role="header">
  <h1><script>document.write(sessionStorage.siteTitle);</script></h1>
</div>

This works the first time the page is loaded but if I change the url var id and reload the page the title remains for the previous page - even though I can see that the correct title has been retrieved from the JSON array. It's as if sessionStorage.siteTitle is cached so the first time I reload with a new url var id it doesn't change - but if I reload again the new title is displayed.

Hopefully that makes sense. I'm pulling my hair out. If anyone has an idea about this - or even an alternate and more appropriate way of having a consistent title in the header of

After initial page load, that bit of javascript is never processed again. It only sets the header once, which it does successfully. Afterwards, you'll have to manually update the h1:

$.get("ajax/siteInfo.php?id=" + getURLvar( 'id' ), function(siteData){
    $('div[data-role="header"] h1').html(siteData.siteTitle);
}, "json");

I would replace the text when the pageshow even is fired. This event fires when a page is requested and shown to the user. Here I am attaching the event to all pages:

$('div[data-role="page"]').live('pageshow', function() {
     // replace header text
     $(this).children('div[data-role="header"] h1').html(sessionStorage.siteTitle);
});

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