jquery ajax调用点击,只能工作一次

我有这个简单的jquery代码。 点击它获取标签的URL,在当前内容旁边加载该页面,滑动它并删除旧内容。 页面的状态与以前完全相同,相同的元素没有额外的类或样式。 问题是下一个ajax调用不起作用。 也许我需要.unbind()一些东西?

我是jquery和javascript的新手,所以我很丢失。 非常感谢你的帮助 :)

 $(document).ready(function(){ loadPage(); }); function loadPage(url) { if (url == undefined) { $('body').load('index.html header:first,#content,footer', hijackLinks); } else { $.get(url , function(data) { $('body').append(data); $('body>meta').remove(); $('body>link').remove(); $('body>title').remove(); $('body').append(direction); sm = $(window).width(); if(direction == "leftnav"){ $('body>header:last,body>#content:last,footer:last').css("left", "-" + sm + "px"); footerheight = $('body>#content:last').outerHeight(false) + $('body>header:last').outerHeight(true) ; $('footer:last').css("top", footerheight); $('body>header,body>#content,footer').css("-webkit-transition-duration","0.5s") $('body>header,body>#content,footer').css("-webkit-transform","translate(" + sm + "px,0px)"); }; if(direction != "leftnav"){ $('body>header:last,body>#content:last,footer:last').css("left", sm + "px"); footerheight = $('body>#content:last').outerHeight(false) + $('body>header:last').outerHeight(true) ; $('footer:last').css("top", footerheight); $('body>header,body>#content,footer').css("-webkit-transition-duration","0.5s") $('body>header,body>#content,footer').css("-webkit-transform","translate(-" + sm + "px,0px)"); }; setTimeout(function(){ $('body>header:not(:last),body>footer:not(:last),body>#content:not(:last)').remove() },500); setTimeout(function() { $('body>header,body>footer,body>#content').removeAttr('style') },500); }); } } function hijackLinks() { $('a').click(function(e){ e.preventDefault(); loadPage(e.target.href); direction = $(this).attr('class'); }); }  

由于您正在动态加载正在替换body内容的内容,因此事件处理程序很可能不会保留。

要解决此问题,您需要调整单击处理程序以使用live()delegate()

 $('a').live("click", function(e){ e.preventDefault(); loadPage(e.target.href); direction = $(this).attr('class'); }); 

对于任何阅读2013年“开启”的人来说,现在“实时”的新方式已被折旧(例如来自wordpress分页):

 /*******ajax pagination*******/ jQuery(document).on('click', '#pagination a', function(e){ e.preventDefault(); var link = jQuery(this).attr('href'); jQuery('#content').html('Loading...'); //the 'main' div is inside the 'content' div jQuery('#content').load(link+' #main'); }); 

.live()函数已被折旧,因此请改用.on()。 显然,jQuery库也是必需的。