如何使用ajax获得onClick和onOpstate的相同功能
how can i get the same function onClick and onpopstate with ajax
我做了一个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);
});
}
相关文章:
- 添加文字和评论功能更新Div
- JavaScript打印功能使日历停止工作
- 每当您在选择器内移动鼠标时,悬停功能就会重复
- 如何防止网页加载后自动启动功能
- 除修剪外的其他功能
- 悬停功能触发器
- 使用angularjs向浏览器发送servlet响应(下载功能)
- 删除CKEditor工具栏按钮,但不删除功能
- 异步facebook功能
- 如何将chrome扩展功能移植到移动设备(特别是jquery和trello)
- jQuery滚动功能只工作一次
- Graphiti中是否有任何工具提示功能
- React redux初始化功能,无论状态变化如何
- 在哪里可以学习ECMAScript标准中尚未包含的JavaScript功能
- 正在获取select上的功能id
- Rhino打印功能
- 使用(navigator.geolocation)检测浏览器功能错误
- 主体单击删除功能上的输入框宽度
- 具有类似onhashchange的相同功能的JavaScript onopstate替代方案
- 如何使用ajax获得onClick和onOpstate的相同功能