将内容加载到iframe时,浏览器后退按钮不起作用

时间:2013-08-21 04:19:26

标签: javascript html iframe browser back-button

我有一个javascript函数用于在用户点击链接时显示一些内容。

function showContent(filename){
  var oldcontent = $('#content').html();
  var srcUrl = getSourceUrl(filename);
  $('#content').html(oldcontent + '<iframe style="width:100%;height=100%;display:block;" src="'+srcUrl+'" />');
}

由于内容已加载到IFrame中,因此URL不会更改,我无法返回到链接使用浏览器后退按钮的上一页。我是一个新手,我试图做这样的事情(愚蠢的实验)。即将“#page2”附加到网址,但是当用户点击后退按钮时,没有任何反应。

var oldcontent = $('#content').html();
var srcUrl = getSourceUrl(filename);
location.href = location.href + '#page2';
$('#content').html(oldcontent + '<iframe style="width:100%;height=100%;display:block;" src="'+srcUrl+'" />');

有谁能告诉我这有什么问题以及如何启用后退按钮功能?

1 个答案:

答案 0 :(得分:0)

试试这个:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Hash Test</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
  </head>
  <body>
    <div id='message-container'></div>
  </body>
  <script>
    var messages = ["Hello. Click anywhere on the page.", "How are you?", "I hope you're fine.", "Have a nice day and hit the back button."];
    var currentMessage = 0;
    var lastMessage = messages.length - 1;

    $(document).click(function() {
      nextMessage();
    });

    function nextMessage() {
      if (currentMessage < lastMessage) {
        currentMessage++;
        updateHash();
      }
    }

    function displayMessage() {
      $("#message-container").text(messages[currentMessage]);
    }

    function updateHash() {
      window.location.hash = "#message" + currentMessage;
    }

    $(window).on("hashchange", function() {
      if (/message\d+/.test(window.location.hash)) {
        currentMessage = window.location.hash.match(/message(\d+)/)[1];
        displayMessage();
      }
    });

    updateHash();
  </script>
</html>