我有一个div(i),其中包含Ajax .load()
的内容加载。
加载div(i)后,有两个锚链接打开上一个或下一个帖子。
这些下一个和上一个链接可以很好地将整个页面重新加载到它们各自生成的URL,但是我需要它们加载到它们首先被加载到的Ajax帖子中。
点击它们时发生的事情是,Ajax div中已加载的当前帖子只是重新加载。下一篇或上一篇文章href
将被忽略。
下一个/上一个帖子的锚点结构:
<div class="previousNav">
<?php $prev_post = get_previous_post();
if (!empty( $prev_post )): ?>
<a href="<?php echo get_permalink( $prev_post->ID ); ?>" rel="<?php the_ID(); ?>">
←</a>
<?php endif; ?>
</div>
<div class="nextNav">
<?php $next_post = get_next_post();
if (!empty( $next_post )): ?>
<a href="<?php echo get_permalink( $next_post->ID ); ?>" rel="<?php the_ID(); ?>">
→</a>
<?php endif; ?>
</div>
以上html的jScript函数:
jQuery(function($){
$(document).ready(function() {
$('.previousNav a').click(function (event) {
event.preventDefault();
var post_id = $(this).attr("rel");
$(".aboveTheFold").load("<?php echo get_site_url(); ?>/ajax-post/",{id: post_id}); console.log();
return false;
});
$('.nextNav a').click(function (event) {
event.preventDefault();
var post_id = $('.nextNav a').attr("rel");
$(".aboveTheFold").load("<?php echo get_site_url(); ?>/ajax-post/",{id: post_id});
return false;
});
});
});
未获得console.log()
的任何输出或Chrome控制台中的任何错误。
这是一个Ajax错误吗?
答案 0 :(得分:1)
使用.on()
方法使用事件委派:
$('body').on('click', '.previousNav a', function (event) {
event.preventDefault();
var post_id = $(this).attr("rel");
$(".aboveTheFold").load("<?php echo get_site_url(); ?>/ajax-post/",{id: post_id});
return false;
});
$('body').on('click', '.nextNav a', function (event) {
event.preventDefault();
var post_id = $('.nextNav a').attr("rel");
$(".aboveTheFold").load("<?php echo get_site_url(); ?>/ajax-post/",{id: post_id});
return false;
});
因为在每次ajax加载后你的.previousNav a
和.nextNav a
会刷新,所以事件处理程序不会
第二次被解雇。但是通过事件委派,您可以将事件处理程序附加到
当前和未来的元素。
参考文献:
.on()
- jQuery API文档答案 1 :(得分:0)
jQuery 1.8及以上
$('.previousNav').on('click', 'a', function (event) {
event.preventDefault();
var post_id = $(this).attr("rel");
$(".aboveTheFold").load("<?php echo get_site_url(); ?>/ajax-post/",{id: post_id}); console.log();
return false;
});
这使用委托来监视'.previousNav'并为所有a
注册所提供的函数,无论它们何时被添加(同样适用于nextNav
)