我有一个用 Javascript 编写的 Ajax 函数,可以在滚动时加载帖子。网格是 Masonry 风格(使用 Colcade JS)。
问题是我找不到将这行 jQuery 代码转换为 Javascript 的方法。我想将 Ajax
data
包装到一个对象中并用它来解析 HTML。
const posts = $(data);
JS:
const grid = document.querySelector(".js-grid");
if (grid) {
// Colcade JS
var colc = new Colcade(grid, {
columns: '.js-grid-col',
items: '.js-grid-article'
});
// Ajax
const current_post_type = grid.dataset.currentPostType;
const posts_myajax = grid.dataset.postsMyajax;
let current_page_myajax = grid.dataset.currentPageMyajax;
const max_page_myajax = grid.dataset.maxPageMyajax;
const ajax_url = grid.dataset.ajaxUrl;
const current_action = grid.dataset.action;
var throttleTimer;
const throttle = (callback, time) => {
if (throttleTimer) return;
throttleTimer = true;
setTimeout(() => {
callback();
throttleTimer = false;
}, time);
};
const handleInfiniteScroll = () => {
throttle(() => {
const endOfPage = window.innerHeight + window.pageYOffset >= document.body.offsetHeight;
if (endOfPage) {
const data = new FormData();
data.append( 'action', current_action );
data.append( 'archive_post_type', current_post_type );
data.append( 'query', posts_myajax );
data.append( 'page', current_page_myajax );
fetch(ajax_url, {
method: "POST",
body: data
})
.then((response) => response.text())
.then((data) => {
if (data) {
const posts = $(data);
colc.append(posts);
current_page_myajax++;
}
});
}
if (current_page_myajax == max_page_myajax) {
removeInfiniteScroll();
}
}, 1000);
};
const removeInfiniteScroll = () => {
window.removeEventListener("scroll", handleInfiniteScroll);
};
window.addEventListener("scroll", handleInfiniteScroll);
}
谢谢你。
编辑
按照@Barmar 的评论,我使用 DOMParser 来解析 HTML。滚动时加载项目,但加载不正确。有些项目重复,有些项目缺失。
const parser = new DOMParser();
const doc = parser.parseFromString(data, "text/html");
let posts = doc.querySelectorAll('.js-grid-article')
if (posts) {
colc.append(posts);
}
我认为这是相当于你的 jQuery 代码的普通 JS:
const parser = new DOMParser();
const posts = parser.parseFromString(data, "text/html");
colc.append(posts);