Modify the url, the page does not refresh

1. Set the anchor point feature (take the code of the tab page in bootstrap as an example)

html:

 1 <div>
 2 
 3   <!-- Nav tabs -->
 4   <ul class="nav nav-tabs" role="tablist">
 5     <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab" onclick="home()">Home</a></li>
 6     <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab" onclick="profile()">Profile</a></li>
 7     <li role="presentation"><a href="#messages" aria-controls="messages" role="tab"data-toggle="tab" onclick="message()">Messages</a></li>
 8     <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab" onclick="setting()">Settings</a></li>
 9   </ul>
10 
11   <!-- Tab panes -->
12   <div class="tab-content">
13     <div role="tabpanel" class="tab-pane active" id="home">home</div>
14     <div role="tabpanel" class="tab-pane" id="profile">profile</div>
15     <div role="tabpanel" class="tab-pane" id="messages">message</div>
16     <div role="tabpanel" class="tab-pane" id="settings">setting</div>
17   </div>
18 
19 </div>

js:

1  index.js:
 2  var currenturl = window.location.href;
 3  if (currenturl.indexOf('#')< 1 ) {
 4      window.location.href = currenturl + '#home' ;
 5 } else {
 6      var hreftype = window.location.hash; // #Following field 
7      $("a[href="+hreftype+"]").click(); // Trigger the click event of this a 
}
 9  10 profile.js:
 11 var currenturl = window.location.href;
 12 if (currenturl.indexOf('#')< 1 ) {
 
   13     window.location.href = currenturl + '#home';
14 } else {
15     var hreftype = window.location.hash;//#后面的字段
16     window.location.href = (currenturl.split("#"))[0]+'#profile';
17     
18 }

Using the anchor point method to switch and refresh the page will also locate the specified page, but if the page content is too long and the scroll bar appears, the anchor point will be located to the clicked a element, and the page will not be topped.

2. Use history.pullState to achieve

1  index.js:
 2  
3  var currenturl = window.location.href;
 4  if (currenturl.indexOf('?')< 1 ) {
 5      window.location.href = currenturl + '?home' ;
 6 } else {
 7      var hreftype = window.location.search.substr(1); // Field 
8 behind ?      $("a[href=#"+hreftype+"]").click(); // Trigger the click event of this a, Note the field stitching # 
9  }
 10  
11  
12  profile.js:
 13  
14  var currenturl = window.location.href;
 15 var newUrl = (currenturl.split("?"))[0];
16 history.pullState('','',newUrl+'?profile');

The above two methods can realize the refresh of the tab page to point to the current page, without jumping to the default home page, and the page will not be automatically refreshed when the url is changed, but the second method is more in line with the actual effect;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324846919&siteId=291194637