简体   繁体   中英

How to enable and disable back button using JavaScript

I am using VS 2010.

I use two links to go back/forward between pages.

Code:

<a href="#" onclick="history.go(-1);return false"><img src="Images/back.jpg" /></a>
<a href="#" onclick="history.go(1);return false"><img src="Images/forward1.jpg"/></a>

It works well. Now I want to enable and disable the links based on browser history.

How do I do this using JavaScript?

As anchors are used for clicking, any other dom element also can be clicked. So,It is visually better to implement this functionality without using hyperlinks. Use code similar as below:

<p id="back"><img src="back.jpg"></p> 
<p id="forward"><img src="forward.jpg"></p>

and event as below:

$("#back").click(function(){
  if(!$(this).hasClass('disabled'))   history.go(-1);
  $(this).addClass('disabled');
  $("#forward").removeClass('disabled');
});

$("#forward").click(function(){
   if(!$(this).hasClass('disabled')) history.go(1);
  $(this).addClass('disabled');
  $("#back").removeClass('disabled');
});

User required style for .disabled .

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