javascript:history.back(-1)问题由<a>

时间:2017-10-21 13:45:56

标签: javascript jquery html back

Hi I am using a Button to go back to the previous page in our app [the code I use ↓ ]

<a class="back-page" href="javascript:history.back(-1)"></a>

This is working perfectly too. My real issue with some ID's in my view page. If a user click on some of the anchot tag with ID's linked, then he has to click that much time Back Button to redirect to the previous page.

What I need is that no matter how much ID's he have click, if he click to the Back Button then the page should redirect to the previous page.

I have tried some method's ↓

First

function goBack() {
    window.history.back();
}
<button onclick="goBack()">Go Back</button>

Second

<a href="javascript: history.go(1)">Go Back</a>

Third

$(".back-page").click(function(event) {
    event.preventDefault();
    history.back(1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="back-page" href="javascript:void(0);">Back</a>

The code of the anchot tag with ID ↓

<ul>
  <li><a href="#t1">Personal Info</a></li>
  <li><a href="#t2">Address(s)</a></li>
  <li><a href="#t3">Social Info</a></li>
  <li><a href="#t4">More Info</a></li>
</ul>

None of this helped me, any help would be highly appreciated.

1 个答案:

答案 0 :(得分:1)

主要问题是单击其中一个ID会添加另一个历史记录条目。为了防止这种情况,我们可以这样做:

document.querySelectorAll("a")
  .forEach(function(link){
     if(link.href.includes( location.href + "#")){
       //we stay on the page, prevent redirects:
       link.addEventListener("click", function(event){
         event.preventDefault(); //the redirect
         //scroll:
         document.getElementById( link.href.split("#")[1] )
         .scrollIntoView();
      });
    }
  });

如果您想更改网址(和历史记录),我们需要计算我们制作的历史记录条目,然后后退按钮需要返回该金额:

var count = 1;

document.querySelectorAll("a")
  .forEach(link =>
     link.onclick = () =>  count++
  );

然后回去:

history.go( - count );