Objective
This is a common requirement: Click on the page number to update pages locally (not overall refresh) and generate historical management. Local refresh is easy to implement, Ajax can meet our needs, but this does not produce historical management, fortunately HTML5 to provide us with a few useful APIs to facilitate the solution to this problem, see below.
Body
One, API
1, Pushstate
Pushstate () has three parameters: a state object, a caption (which is now ignored), an optional URL address.
State: The status information corresponding to the URL to jump to.
Title: empty string (may be useful later).
URL: The URL address to jump to, not cross-domain.
Action: adds the current URL and history.state to the history and replaces the current with the new state and URL. does not cause page refreshes.
2, Replacestate
The History.replacestate () operation is similar to History.pushstate (), except that the Replacestate () method modifies the current history entry rather than creating a new entry.
3, Window.onpopstate
History.go and History.back (including the user by the browser history forward Back button) triggered, and when the page is not brush (because the use of pushstate modified history) will trigger the Popstate event, when the event occurs, the browser from the history to take out the URL and the corresponding St The ATE object replaces the current URL and history.state. History.state can also be obtained through event.state.
Second, realize
The scene is very simple, click on the button below the div in a different picture and title, using Ajax refresh, and create a history of management.
<p class= "page" >
<a href= "javascript:;" >[<span>1</span>]</a>
<a href= "javascript:;" >[<span>2</span>]</a>
<a href= "javascript:;" >[<span>3</span>]</a>
<a href= "javascript:;" >[<span>4</span>]</a>
</p>
<div>
<p class= " Title "></p>
</div>
Core code
function SetUrl (page) {
var url = location.pathname + '? page= ' + page;
History.pushstate ({
url:url
}, ", URL);
}
Add an entry to the history record each time you click the button
Note that you need to load the first load to replace the history
(function () {
///default display first page
var url = location.pathname + '? page=1 ';
Modify Current History
History.replacestate ({
url:url
}, ', URL);
} " ()
Listens for the Popstage event of the window, takes the page number of the current history when the event occurs, and then executes the Ajax
Window.addeventlistener (' Popstate ', function () {
var page = GetPage ();
XHR (page);
})
This is how the skeleton is.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.