0

我正在尝试做一个 pushState 网站,好吧,问题完全是在 .nav 中消失了。

不知道怎么回事,可能是jquery版本,所以这里是我的index.html代码:

        <!doctype html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
    <script type="text/javascript" src="assets/application.js"></script>
    <title>One</title>
  </head>
  <body>
  <audio controls>
<source src="mp.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
    <div id="body">
<div id="menu">
<div class="nav">
<a href="two.html">d</a>
</div>
</div>
</div>
  </body>
</html>

和 application.js:

$(function(){
    var replacePage = function(url) {
        $.ajax({
            url: url,
            type: 'get',
            dataType: 'html',
            success: function(data){
                var dom = $(data);
                var title = dom.filter('title').text();
                var html = dom.filter('.nav').html();
                $('title').text(title);
                $('.nav').html(html);
            }
        });
    }

    $('a').live('click', function(e){
        history.pushState(null, null, this.href);
        replacePage(this.href);
        e.preventDefault();
    });

    $(window).bind('popstate', function(){
        replacePage(location.pathname);
    });
});

这是JSFiddle

二.html:

<!doctype html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
    <script type="text/javascript" src="assets/application.js"></script>
    <title>One</title>
  </head>
  <body>
  <audio controls>
<source src="mp.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
    <div id="body">
<div id="menu">
<div class="nav">
<a href="index.html">djbghasighaslashb</a>
</div>
</div>
</div>
</body>
</html>
4

1 回答 1

0

如果您不确定所需的元素是在根级别还是在 dom 树的某个深处,则将完整的 html 响应包装到根元素中可能会很有用:

success: function( data ){

  // create a single container element, and put the html response into it
  var dom = $('<div>').html( data );

  // now you never have to use .filter(), just .find()
  var title = dom.find('title').text();
  var html  = dom.find('.nav').html();
  ...
}
于 2013-09-29T19:03:25.620 回答