当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to re-attach jQuery functions after AJAX content load?

问题描述:

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

jQuery(document).ready(function(){

jQuery(".accordion").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:

  • 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

网友答案:

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();
    }
});

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

网友答案:

I have a similar issue with jQuery widgets. What I did was use the ajaxComplete method to attach the widgets.

$(document).ajaxComplete(function()
    {
        $(".accordion").accordion();
    });

that way, the function gets called every time an AJAX method is complete and will attach the accordion to any new elements with class accordion

网友答案:

http://api.jquery.com/on/

"Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time."

jQuery(document).on("change", ".accordion", function() {
  jQuery(".accordion").accordion();
});
网友答案:

You can check for ".accordeon"-length. Just create a function...

function init_accordeon(){
    if($('.accordeon').length) {
        $(".accordon").accordeon();
    }
}

and than call this function after your ajax_calls.

网友答案:

you can trigger custom events after ajax call.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>on demo</title>
  <style>
  p {
    color: red;
  }
  span {
    color: blue;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>

<script>
$( "p" ).on( "myCustomEvent", function( event, myName ) {
  $( this ).text( myName + ", hi there!" );
  $( "span" )
    .stop()
    .css( "opacity", 1 )
    .text( "myName = " + myName )
    .fadeIn( 30 )
    .fadeOut( 1000 );
});
$( "button" ).click(function () {
  $( "p" ).trigger( "myCustomEvent", [ "John" ] );
});
</script>

</body>
</html>
分享给朋友:
您可能感兴趣的文章:
随机阅读: