[英]live() alternative on() not working jQuery 1.9
我有代码做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) {
谢谢 :)
你不是简单地s/live/on
,你需要阅读on()
的文档来查看更新代码所需的更改( on
类似于旧的delegate()
)。
如果你想它到底工作就像live()
尝试...
$(document).on('click', '.nav-menu li a,#nav-below a,#main a', function(e) { });
但是,如果可以的话,最好选择最常见的持久性祖先。 这意味着事件不必一直到document
处理。 例如, body
可能覆盖99.9%的情况。 但是,它可能更像是#some-container
。
为方便使用,您可以使用以下内容:
$.fn.follow = function (event, callback) {
$(document).on(event, $(this).selector, callback);
}
你可以像以下一样使用它:
$("#myselector").follow("click",function(){
/*some callback code*/
});
您仍然可以在插件中使用事件数据
$("#expform").follow("submit",function(e){
e.preventDefault();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.