首页 > 解决方案 > 在循环中在 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,但页面上的旧项目两次应用相同的脚本,这是一个问题。

标签: javascriptjqueryajax

解决方案


只需定义要在函数中运行的代码。在文档就绪时调用它并将其绑定到 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();

推荐阅读