如何使用ajax获得onClick和onOpstate的相同功能

how can i get the same function onClick and onpopstate with ajax

本文关键字:功能 onOpstate 何使用 ajax 获得 onClick      更新时间:2023-09-26

我做了一个AJAX导航,在菜单点击时有一个渐变效果,我用history.pushstate来获取我的URL链接,所以现在我如何在onpopstate函数上产生同样的效果?(当用户点击浏览器的返回按钮时):

这是我的代码:

$(document).ready(function() {
  $("#menu a").click(function() { 
    var page = $(this).attr("href");
    $.ajax({
      url: "pages/" + page,
      cache: false,
      success: function(html) {
        afficher(html, page);
        history.pushState({ key: 'value'}, 'hash', page);
      }, 
      error:function(XMLHttpRequest, textStatus, errorThrown) {
        afficher("erreur lors du chagement de la page");
      }
    });
    return false;
  });
  $('#container').on('click', '.vs-transform a', function() {
    var page = $(this).attr("href");
    $.ajax({
      url: "pages/" + page,
      cache: false,
      success: function(html) {
        afficher(html, page);
        history.pushState({key : 'value'}, 'hash', page);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        afficher("erreur lors du chagement de la page");
      }
    });
    return false;
  }); 
  window.onpopstate = function(event) {
    if (event.state === null) {
      // Here have to make the same fadeout-in effect but how to get my data variable? 
    }
  };
});

function afficher(data, page) {
  $("#container").delay( 100 ).fadeOut(400, function() {
    $("#container").empty();                
    $("#container").append(data);
    $("#container").fadeIn(500);
  });
}

我认为你只需要提取你的函数并对其进行操作,或者以不同的方式调用它,因为你没有一个真正的带有href的DOM元素

function getYourData (someHref) { 
  var page = someHref || $(this).attr("href"); // override or default
  $.ajax({
    url: "pages/" + page,
    cache: false,
    success: function (html) {
      afficher(html, page);
      history.pushState({ key: 'value'}, 'hash', page);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      afficher("erreur lors du chagement de la page");
    }
  });
  return false;
}
$(document).ready(function() {
  $("#menu a").click(getYourData);
  $('#container').on('click', '.vs-transform a', getYourData);
  window.onpopstate = function(event) {
    if (event.state === null) {
      getYourData(document.referrer); // some href
    }
  };
});

function afficher(data, page) {
  $("#container").delay( 100 ).fadeOut(400, function() {
    $("#container").empty();                
    $("#container").append(data);
    $("#container").fadeIn(500);
  });
}