如何为用javascript加载的内容添加书签

I have one div on the page that is supposed to hold content and a number of links that I used to load which content.

<div id="thecontent">
</div>

<div id="callers">
 <div class="caller">1234</div>
 <div class="caller">15</div>
 <div class="caller">9</div>
 <div class="caller">324</div>
</div

I use jquery to monitor when one of the .caller is clicked, and I then get the record from the database and display it in #thecontent.

How can I also change the url so that it reflects the record being viewed. I mean a url that looks something like this. Is there something I need to do in the html markup or in the jquery to make this happen?

http://site.com/#1234

in the caller selector:

location.href = '#'+$(this).html();

You have two options:

Option 1

Make the "caller" menu use actual anchor elements like <a href="#1234">1234</a>. Add a click event handler to intercept and do your XHR fetch.

Option 2

On your click handler, set window.location.hash to your target.

For both options: When your page loads, check the value of window.location.hash to see if it comes with a target and fetch that target if there is one specified.

Firstly to set the hash value, you can use

window.location.hash = '1234';

You can also read this value when the page loads using:

window.location.hash.substr(1); // .hash also returns the '#' character, so use substr to remove it

With that in mind, you can then do this in your .ready()

$(function() {
  var hash = window.location.hash.substr(1);
  if(hash != '') {
    $('#callers .caller:contains('+hash+')').click();
  }
});

In your .caller click() function, you will need to update the hash as well.

Have a look at http://www.20thingsilearned.com/, the javascript for the history http://www.20thingsilearned.com/js/twentythings.history.js should give you everything you need.

It uses the modern history management calls, pushstate() and etc if they are available, or fallbacks to updating the href with hash tags, and checking for the presence of said hashtags to work out which content should be displaying. It's really nice.