简体   繁体   中英

'back button' to revert to previous state of a page?

I have a home page that has extensive jQuery...Hiding and showing divs based on clicks of tabs etc. Within the shown div's there are links to other pages which postback and get the new page.

Now i would like a 'back' button on the page to go back to the previous state of the page when the user clicked on it. So if they had the Sell_your_books div shown and 'Sell_your_books tab' selected when they clicked the link, I would like to have a back button going to the home page with the Sell_your_books div shown and 'Sell_your_books tab'selected.

I know that I will have to parse (POST) a variable to the homepage to achieve this with php but I am unsure of the correct way to implement it.

Thanks

Use hash hyperlinks and the hashchange event. In jQuery:

$(window).on('hashchange',function() {
    var hash = location.hash.substring(1); // strip the leading # symbol
    // now run code based on whatever the value of 'hash' is
});

HTML

<a href="#hash1">function A</a>
<a href="#hash2">function B</a>

Now, whenever the user clicks the browser's "back" button (or an HTML button that triggers history.go(-1)) , it will go back to whatever hash was previously selected and trigger the hashchange event again.

MORE DETAILS

Create a hidden input field and fill this one with the current active tab.

<form>
 ..
 <input type="hidden" name="currentTab" value="" />

</form>

A bit of jQuery to set the right value:

$( YOUR TAB SELECTOR ).on('click', function() { 
 $('input[name=currentTab]').val( $(this).attr('id') ); 
});

In the PHP-Script which handles you data, you can create a back link like this:

<?php

 if( isset($_POST['currentTabe']) && $_POST['currentTab'] != '' ) {
   $backLink = "your_page.php?tab=" . $_POST['currentTab'];
 }

?>

If you now call your site with tabs trough the backlink, you can create a additional document.ready event, which set's the active tab to the PHP $_GET Parm.

<script type="text/javascript">
 <?php
  if( isset($_GET['tab']) && $_GET['tab'] != '' ) {
 ?>
  jQuery(document).ready( function() {

   var tab = $('#'+ <?=htmlspcialchars( $_GET['tab'] )?>);
   if( tab.length <= 0 ) return false; //element not found

   //active tab
   tab.toggle('click'); //click or do something else to activate the current tab

  });
 <?php 
  }
 ?>
</script>

Attention: Beware of XSS (Cross-Site-Scripting), so check your $_POST and $_GET for correct values.

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