加载AJAX内容后如何重新附加jQuery函数? [英] How to re-attach jQuery functions after AJAX content load?

查看:81
本文介绍了加载AJAX内容后如何重新附加jQuery函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这种方式调用了一些jQuery UI函数:

There are a few jQuery UI functions that I call this way:

jQuery(document).ready(function(){
    jQuery(".accordion").accordion();
});

但是我的页面是基于AJAX的,有些页面可能会使用手风琴,有些页面可能会不使用它.大约有30多个其他功能需要重新连接,这是一个有问题的开发任务.有什么聪明的方法可以解决此问题,以便每个新的.accordion都可以自动将其附加?

But my page is AJAX based and some pages may use accordion, some may not use it. There are like 30+ other functions that would need to be re-attached which is a problematic development task. Is there any clever way to fix this so that every new .accordion gets this attached automatically?

可能的解决方案以及它们为什么不起作用:

Possible solutions and why they won't work:

  • 在AJAX通话完成时触发文档准备好,但这是不可能的
  • 没有load()是不可行的,因为它是CMS,用户可以在其中安装插件-这意味着未知数量的未知功能(仅使用jQuery(document).ready();
  • 即可添加)
  • ajaxComplete上重新附加功能-具有未知数量的未知功能,每次安装或卸载jQuery插件时,如果不修改AJAX脚本就无法使用
  • triggering document ready on AJAX call finish would be ideal but that's not possible
  • having load() is not an option because it's a CMS where users can install plugins - that means unknown number of unknown functions that plugins add only using jQuery(document).ready();
  • re-attach functions on ajaxComplete - with unknown number of unknown functions this won't work without modifying AJAX script each time you install or uninstall a jQuery plugin

推荐答案

您可以使用DOMNodeInserted事件并检查手风琴类.

You can use the DOMNodeInserted event and check for the accordion class.

document.addEventListener('DOMNodeInserted', function(e) {
    var el = $(e.target);
    if(el.hasClass('accordion')) {
        el.accordion();
    }
});

使用DOMNodeInserted的示例: http://jsfiddle.net/qErHs/

Example use of DOMNodeInserted: http://jsfiddle.net/qErHs/

这篇关于加载AJAX内容后如何重新附加jQuery函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆