【发布时间】:2013-05-03 15:44:38
【问题描述】:
我有代码做 ajax 方法来加载新内容
但我对新内容有疑问,链接没有应用我喜欢的操作
preventDefault 和 ajax 方法,就在加载新内容之后
单击链接会使页面重新加载,就像根本没有 ajax 代码一样
在 JQ 1.8 中使用 live() 方法工作,但在更新 jQuery 后,使用 on() 方法无法正常工作
旧代码可以正常工作,没有问题
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
function loadContent(url){
$.ajax({
url: url,
dataType: 'html',
cache: false
}).done(function(html){
var $html = $(html);
$('title').html($html.filter('title').text());
$('#main').replaceWith($html.find('#main'));
$('.nav-menu').replaceWith($html.find('.nav-menu'));
$('.nav-below').replaceWith($html.find('.nav-below'));
});
}
$(function(){
// Get The Content Action
$('.nav-menu li a,#nav-below a,#main a').live('click',function(e) {
href = $(this).attr("href");
loadContent(href);
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
// go top after showing the content
$('html, body').animate({scrollTop:0}, 'slow');
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event){
loadContent(location.pathname);
$('html, body').animate({scrollTop:0}, 'slow');
};
});
</script>
新更新的代码
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function loadContent(url){
$.ajax({
url: url,
dataType: 'html',
cache: false
}).done(function(html){
var $html = $(html);
$('title').html($html.filter('title').text());
$('#main').replaceWith($html.find('#main'));
$('.nav-menu').replaceWith($html.find('.nav-menu'));
$('.nav-below').replaceWith($html.find('.nav-below'));
});
}
$(function(){
// Get The Content Action, ‡‡=‡=‡=‡=L0000K HERE=‡=‡=‡=‡‡ Not workin JQ 1.9
$('.nav-menu li a,#nav-below a,#main a').on('click',function(e) {
href = $(this).attr("href");
loadContent(href);
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
// go top after showing the content
$('html, body').animate({scrollTop:0}, 'slow');
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event){
loadContent(location.pathname);
$('html, body').animate({scrollTop:0}, 'slow');
};
});
</script>
问题就在这里
$('.nav-menu li a,#nav-below a,#main a').on('click',function(e) {
谢谢你:)
【问题讨论】:
-
"...无法正常工作..."。语法错误,请查看
on授权手册。 -
这不是使用
on完成事件委托的方式。你读过api.jquery.com/live吗? -
顺便说一句,有数百个类似的问题和重复:stackoverflow.com/questions/8867194/…,stackoverflow.com/questions/9484295/…。如果只是人们搜索了 5 分钟...我通过查找“在不工作的 jquery stackoverflow 上”找到了它并 baam 了两个第一个结果。
标签: javascript ajax jquery