提问人:Mathieu Préaud 提问时间:11/9/2023 最后编辑:Mathieu Préaud 更新时间:11/10/2023 访问量:49
在 Ajax 函数中将 jQuery 对象转换为 javascript
Convert jQuery object to javascript inside Ajax function
问:
我有一个用 Javascript 编写的 Ajax 函数,用于在滚动时加载帖子。网格是砌体风格(使用 Colcade JS)。
问题是我找不到将这行jQuery代码转换为Javascript的方法。我想将 Ajax 包装成一个 objet 并使用它来解析 HTML。data
const posts = $(data);
The 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);
}
答:
0赞
Barmar
11/10/2023
#1
我认为这是您的 jQuery 代码的 vanilla JS 等价物:
const parser = new DOMParser();
const posts = parser.parseFromString(data, "text/html");
colc.append(posts);
评论
0赞
Mathieu Préaud
11/10/2023
谢谢。我也尝试过这个等效项,但它在控制台中产生了一个错误。错误指向colcade js文件:此行。最后,我不知道这个问题是否仅与 Colcade 或我的代码有关。Unhandled Promise Rejection: HierarchyRequestError: The operation would yield an incorrect node tree
fragment.appendChild( elem );
0赞
Barmar
11/10/2023
不幸的是,Colcade 文档似乎对此没有非常详细。我不确定为什么它不喜欢这个。
0赞
Mathieu Préaud
11/10/2023
我也不确定。无论如何,非常感谢您的帮助。多亏了你,我发现:)DOMParser
评论
DOMParser
Colcade.append()
$()
.append()
DOMParser