简体   繁体   中英

jQuery not affecting content loaded by AJAX

I have a div element, which when clicked will toggle a class on it's parent.

$('.q-header').on('click', function() {
    $(this).parent('.question-wrap').toggleClass('miniturised');
});
// the 'miniturised' class hides child elements.
// therefore when q-header is clicked the child elements are toggled

I have a button on my site, when clicked, it will load one of the aforementioned div elements to the site via AJAX.

$('#addqs').on('click', function() {
    var response;
    $.ajax({ type: "GET",   
         url: "./qt-single-line.html",   
         async: false,
         success : function(text)
         {
             response = text;
         }
    });
    $('#final-row').before(response);
    return false;
});

The divs loaded via AJAX are unaffected by the first function which toggles the class 'miniturised'. Why is the new AJAX content not affected by my JS?

Edit: The HTML element looks like so

<div class="question-wrap miniturised">
    <div class="q-header">
        <span></span>
    </div>
    <div class="q-body">
    </div>
</div>

On a normal DOM element, when I click q-header, miniturise is toggled. This doesn't work on dynamic elements, I know this. I want to know how to solve this, please.

Your newly created element is not already in the dom.

try:

$(document).on('click', '.q-header', function() { 
    $(this).parent('.question-wrap').toggleClass('miniturised');
 });

Events associated with pre-loaded elements works fine, but when you content is loaded dynamically via AJAX calls event handlers are not associated with them. One thing that you can do in this case is attach event to DOM elements via there parents which is available on page load.

$("parentSelect").on('click', 'childSelector', function() {
  // Do this on click.
});

Make sure one thing that you parentSelector should be available at the time of page load.

From the jQuery API :

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler,

You'll need to bind any new HTML seperately. Your initial on binding doesn't apply to new elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM