简体   繁体   中英

jQuery does not load on Ajax

Im currently trying to do some work on some code I did not write or fully understand. The page dynamically calls in content with AJAX. I am trying to manipulate that content but of course because the page has already been loaded when I apply it to the dynamic content it gets ignored. Here are some basic examples of the jQuery i'm trying to call:

$(".check").each(function() {
    $(this).hide();
    var $image = $("<img src='img/checked.png' />").insertAfter(this);
    $image.click(function() {
        var $checkbox = $(this).prev(".check");
        $checkbox.prop('checked', !$checkbox.prop('checked'));

        if ($checkbox.prop("checked")) {
            $image.attr("src", "img/checked.png");
        } else {
            $image.attr("src", "img/unchecked.png");
        }
    })
});

if ($(window).width() < 500) {
    $('.panel-collapse').removeClass('in');
} else {
    $('.panel-collapse').addClass('in');
}

How can I get this to work with ajax please?

Use it in this way.

$image.on('click',function() {
        // your script 
})

As you adding content dynamically it need event delegation .

UPDATE :

 $("some_parent_id_or_class").on('click','img_with_some_class_or_id',function(){

    //your script
 })

eg

 $("some_parent_id_or_class").on('click','img',function(){

    //your script
 })

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