javascript - 在循环中在 AJAX 之后加载 Jquery
问题描述
我有这个代码:
document.addEventListener('DOMContentLoaded', function PostLinkHome() {
jQuery(function($) {
$('.post-link-home').find('.elementor-post').each(function() {
let link = $(this).find('a').attr('href');
$(this).wrapAll(document.createElement('a'));
$(this).closest('a').attr('href', link);
});
jQuery(document).ajaxComplete(function() {
PostLinkHome();
});
});
});
PostLinkHome()
假设在加载 Ajax 之前和之后运行 Jquery 函数。
我试图这样做:
jQuery(document).bind('ready ajaxComplete', function($) {
$('.post-link-home').find('.elementor-post').each(function() {
let link = $(this).find('a').attr('href');
$(this).wrapAll(document.createElement('a'));
$(this).closest('a').attr('href', link);
});
});
但这没有用。
问题是代码可以工作,但是一旦加载了 Ajax,它就会再次加载 jQuery,到循环中的先前项目,这些项目在 Ajax 加载更多内容之前已经应用了函数。
这导致 Ajax 项目应用了 jQuery,但页面上的旧项目两次应用相同的脚本,这是一个问题。
解决方案
只需定义要在函数中运行的代码。在文档就绪时调用它并将其绑定到 Ajax 调用。(旁注:似乎很奇怪,您会在每次 Ajax 调用上运行此代码,而不仅仅是您创建的返回内容的代码)
function PostLinkHome() {
$('.post-link-home .elementor-post').each(function() {
const elem = $(this);
// if parent is already a link, just exit out
if(elem.parent().is('a')) return;
const link = elem.find('a').attr('href');
elem.wrapAll(document.createElement('a'));
elem.closest('a').attr('href', link);
});
}
// Then bind the event and call the function
jQuery(function () {
jQuery(document).ajaxComplete(PostLinkHome);
PostLinkHome();
});
似乎很奇怪,因为此代码会将链接放入链接中?我猜你会想要打开初始链接。
const linkElem = elem.find('a');
const link = linkElem.attr('href');
linkElem.children().unwrap();
推荐阅读
- php - PHP未能将文件夹A复制到文件夹B
- javascript - 如何根据下拉列表中的用户选择动态填充表格
- java - 我应该在哪里调用我的更新地图函数?我需要在我的异步任务之后调用它?
- node.js - npm install 挂在 loadIdealTree:loadAllDepsIntoIdealTree: sill install loadIdealTree
- express - Redis mocha 测试用例问题
- python-3.x - OSError:[Errno 22] Invalid argument 读取 python 日志配置文件时
- sql - sqlserver 2012 中不允许对系统目录进行临时更新
- node.js - 承诺多方
- java - 在 BlankFragment 上看不到 RecyclerView、CardView
- javascript - 下拉菜单不起作用