简体   繁体   中英

onpopstate returning data twice

I've started to play around with onpopstate but ran into a problem. Whenever I click the back button on my browser, the url does change accordingly but the page code is loaded twice so I receive two lists and two div's. Why is is it producing double the code and how do I fix it? The sample code is below.

<style type="text/css">

div {width: 200px; height: 200px; border: 1px solid;}

</style>

<ul>

   <li class="sour">

   <input type="button" value="1"/>

   </li>

</ul>

<script type="text/javascript" >


$('ul li:nth-child(1)').click(function() {
var url = $(this).index();  
$('#insert').load('1.php');
window.history.pushState('', '', 'test1.php?challenge=' + url);
e.preventDefault();
});


window.onpopstate = function(event) {
  $('#insert').load(location.pathname); 
};

</script>


<div id="insert">

<p>hello there</p>

</div>

Here is the contents of 1.php

<p>first file</p>

Here is a link to some screenshots I took of what visually happens. The first image is when I first load the screen. the second image is what happens when I press the button 1. The third image is what happens when I click back on my browser.

http://imgur.com/Nsqej,E1Ydc,sFCLl#0

According to the problem sequence you describe, onpopstate will load the contents of test1.php into the #insert div. Since the landing page was also test1.php this will result in the duplication seen in your screenshots.

You could make this someone else's problem by using jquery-pjax . If you're not tied to jquery there are also other solutions out there that are probably easier than rolling your own.

您可能在某处两次包含了jQuery库。

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