我正在 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');
});
并且對 post grid 的查詢(“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 呼叫之后使腳本作業,但我找不到解決方法。有人有什么建議嗎?我想應該不會很復雜。
謝謝!
uj5u.com熱心網友回復:
問題是: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 '<br>');
follower.addClass('active');
});
$('body').on('mouseleave', '.animated-cursor', function () {
follower.removeClass('active');
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/461020.html
標籤:javascript php jQuery 阿贾克斯
