我正在 WordPress 上构建自己的作品集网站,并在没有插件的情况下编写几乎整个代码。该网站的主页带有动态“自定义帖子类型”网格,我已根据帖子分类/类别实现了 Ajax 过滤器,并根据过滤器对帖子重新排序。该脚本在 script.js 上运行:
(function ($) {
$(document).ready(function () {
$(document).on('click', '.js-filter-item', function (e) {
e.preventDefault();
$('.js-filter-item').removeClass('active');
$('.js-filter').addClass('fade');
$(this).addClass('active');
setTimeout(function () {
$('.js-filter').removeClass('fade');
}, 500);
var category = $(this).data('category');
$.ajax({
url: wpAjax.ajaxUrl,
data: { action: 'filter', category: category },
type: 'POST',
success: function (result) {
// $('.js-filter').html(result);
setTimeout(function () {
$('.js-filter').html(result);
}, 200);
},
error: function (result) {
console.warn(result);
}
})
});
});
我还实现了一个自定义工具提示,它跟随光标并在悬停时显示帖子标题,如下所示。这是在主页标签之间运行的php文件:
var follower = $('.cursor-follower');
var posX = 0,
posY = 0;
var mouseX = 0,
mouseY = 0;
$('body').on('mousemove', function (e) {
mouseX = e.clientX;
mouseY = e.clientY;
posX += (mouseX - posX) / 2;
posY += (mouseY - posY) / 2;
$('.cursor-follower').css(
'top', (posY - 20) + 'px'
);
$('.cursor-follower').css(
'left', (posX + 50) + 'px'
);
});
$('.animated-cursor').on('mouseenter', function () {
console.log('olaaaaa');
var dataTitle = $(this).attr('data-cursor-title');
// var dataTags = $(this).attr('data-cursor-tags');
follower.html(dataTitle + '<br>');
follower.addClass('active');
});
$('.animated-cursor').on('mouseleave', function () {
follower.removeClass('active');
});
以及对帖子网格的查询(“animated-cursor”类和 data-cursor-title 是相关属性):
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="reveal item animated-cursor" data-cursor-title="<?php the_title(); ?>">
<a href="<?php the_permalink(); ?>">
<?php $pagina = get_page_by_title('<?php the_title(); ?>') ?>
<img src="<?php the_field('imagem_capa', $pagina); ?>" alt="">
<div class="post-info">
<div>
<h3><?php echo wp_strip_all_tags(get_the_term_list( $post->ID, 'portfolio_cat', '', ', ', '' )) ?></h3>
<h2><?php the_title(); ?></h2>
</div>
</div>
</a>
</div>
<?php
endwhile;
endif;
wp_reset_postdata();
die();
问题:使用 Ajax 过滤器后,自定义光标工具提示在元素悬停时不起作用。页面加载后一切都按计划运行良好,但 Ajax 运行后任何时候都不会运行。
据我所知(我是 php、ajax、js 的初学者),我的脚本只能访问页面加载时准备好的元素。我尝试让脚本在 Ajax 调用后正常工作,但找不到解决方法。有人有什么建议吗?我想它一定不会很复杂。
谢谢!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
问题是:JavaScript 绑定在现有的 DOM 上,它在第一次渲染时有效。 但是在ajax调用之后,新的DOM将被追加到HTML中。新的 DOM 不会绑定功能,因此悬停不起作用。
解决方案是,不要将事件绑定到 DOM 本身。您可以将事件侦听器绑定到父注释或页面主体上 例如
$('body').on('mouseenter', '.animated-cursor', function () { console.log('olaaaaa'); var dataTitle = $(this).attr('data-cursor-title'); // var dataTags = $(this).attr('data-cursor-tags'); follower.html(dataTitle + ''); follower.addClass('active'); }); $('body').on('mouseleave', '.animated-cursor', function () { follower.removeClass('active'); });