我有一段关于加载新内容的ajax方法的代码。
但是我遇到了新内容的问题,链接没有应用我设置的操作,比如preventDefault和ajax方法,在加载新内容后点击链接会使页面重新加载,就好像根本没有ajax代码一样。
在JQ1.8中使用live()方法可以很好地工作,但在更新jQuery之后,使用on()方法不如预期的那样工作。
新更新的代码
这里的问题是:
谢谢:)
但是我遇到了新内容的问题,链接没有应用我设置的操作,比如preventDefault和ajax方法,在加载新内容后点击链接会使页面重新加载,就好像根本没有ajax代码一样。
在JQ1.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
的手册。 - elclanrson
进行事件委托的正确方式。你是否阅读过http://api.jquery.com/live/? - Bergi