code

콘텐츠가 AJAX를 통해로드 된 후 jQuery가 작동하지 않음

codestyles 2020. 12. 27. 10:53
반응형

콘텐츠가 AJAX를 통해로드 된 후 jQuery가 작동하지 않음


이 페이지 나는 jQuery를 팝업 창을 썸네일 크기 조정 이미지를 가지고있다. 축소판 위에 마우스를 올려 놓으면 이미지 크기가 완벽하게 조정됩니다. 또한 바닥 글에있는 커다란 노란색 TV 버튼 "QuickBook TV"를 클릭하면 원하는대로 팝업이 완벽하게 나타납니다.

그러나 "Next"또는 "Prev"버튼을 클릭하면 AJAX가 새 콘텐츠를로드하는 데 사용되며 jQuery가 더 이상 팝업 또는 축소판 이미지에 대해 작동하지 않습니다. 이 문제에 대한 정보를 찾기 위해 여러 포럼을 검색했지만 jQuery에 대한 지식이 제한되어있어서 무엇을해야하는지 이해할 수 없었습니다.

다음은 팝업 jQuery입니다.

$(document).ready(function() {

        $(".iframe").colorbox({ iframe: true, width: "1000px", height: "500px" });
        $(".inline").colorbox({ inline: true, width: "50%" });
        $(".callbacks").colorbox({
            onOpen: function() { alert('onOpen: colorbox is about to open'); },
            onLoad: function() { alert('onLoad: colorbox has started to load the targeted content'); },
            onComplete: function() { alert('onComplete: colorbox has displayed the loaded content'); },
            onCleanup: function() { alert('onCleanup: colorbox has begun the close process'); },
            onClosed: function() { alert('onClosed: colorbox has completely closed'); }
        });

        //Example of preserving a JavaScript event for inline calls.
        $("#click").click(function() {
            $('#click').css({ "background-color": "#f00", "color": "#fff", "cursor": "inherit" }).text("Open this window again and this message will still be here.");
            return false;
        });
    });

그리고 이것은 축소판 jQuery입니다.

$(function() {

var xwidth = ($('.image-popout img').width())/1;
var xheight = ($('.image-popout img').height())/1;

$('.image-popout img').css(
        {'width': xwidth, 'height': xheight}
); //By default set the width and height of the image.

$('.image-popout img').parent().css(
        {'width': xwidth, 'height': xheight}
);

$('.image-popout img').hover(
    function() {
        $(this).stop().animate( {
            width   : xwidth * 3,
            height  : xheight * 3,
            margin : -(xwidth/3)
            }, 200
        ); //END FUNCTION

        $(this).addClass('image-popout-shadow');

    }, //END HOVER IN
    function() {
        $(this).stop().animate( {
            width   : xwidth,
            height  : xheight,
            margin : 0
            }, 200, function() {
                $(this).removeClass('image-popout-shadow');
    }); //END FUNCTION

    }
);

});

jQuery 선택기는 코드가 실행될 때 DOM에 존재하는 일치하는 요소를 선택하고 동적으로 업데이트하지 않습니다. .hover()이벤트 핸들러 추가 와 같은 함수를 호출하면 해당 요소에만 추가됩니다. AJAX 호출을 수행하고 페이지의 섹션을 바꿀 때 이벤트 핸들러가 바인딩 된 요소를 제거하고 새 요소로 대체합니다. 이러한 요소가 이제 해당 선택자와 일치하더라도 수행 할 코드가 이미 실행 되었기 때문에 이벤트 핸들러가 바인딩되지 않습니다.

이벤트 핸들러

특히 이벤트 핸들러 (예 :)의 .click()경우 이벤트 위임을 사용하여이 문제를 해결할 수 있습니다. 기본 원칙은 모든 동적 (AJAX로드 된) 콘텐츠를 포함 할 정적 (페이지가로드 될 때 존재하고 대체되지 않음) 요소에 이벤트 핸들러를 바인딩하는 것입니다. 이벤트 위임에 대한 자세한 내용은 jQuery 문서를 참조하십시오 .

당신을 위해 click이벤트 핸들러, 업데이트 된 코드는 다음과 같을 것이다 :

$(document).on('click', "#click", function () {
    $('#click').css({
        "background-color": "#f00",
        "color": "#fff",
        "cursor": "inherit"
    }).text("Open this window again and this message will still be here.");
    return false;
});

이는 이벤트 핸들러를 전체 문서에 바인딩합니다 (따라서 페이지가 언로드 될 때까지 제거되지 않음) . 속성이 click있는 요소의 이벤트에 반응합니다 . 이상적으로는 DOM에서 동적 요소에 더 가까운 것을 사용하는 것이 좋습니다 (아마도 항상 거기에 있고 모든 페이지 콘텐츠를 포함하는 페이지). 그러면 효율성이 약간 향상되기 때문입니다.idclick<div>

하지만 문제는 처리해야 할 때 발생합니다 .hover(). hoverJavaScript 에는 실제 이벤트 가 없습니다 . jQuery는 이벤트 핸들러를 mouseentermouseleave이벤트 에 바인딩하는 편리한 약어로 해당 기능을 제공 합니다. 그러나 이벤트 위임을 사용할 수 있습니다.

$(document).on({
    mouseenter: function () {
        $(this).stop().animate({
            width: xwidth * 3,
            height: xheight * 3,
            margin: -(xwidth / 3)
        }, 200); //END FUNCTION

        $(this).addClass('image-popout-shadow');
    },
    mouseleave: function () {
        $(this).stop().animate({
            width: xwidth,
            height: xheight,
            margin: 0
        }, 200, function () {
            $(this).removeClass('image-popout-shadow');
        }); //END FUNCTION

    }
}, '.image-popout img');

jQuery 플러그인

이벤트 핸들러 바인딩을 다룹니다. 그러나 그것이 당신이하는 전부는 아닙니다. 또한 jQuery 플러그인 (colorbox)을 초기화하고 요소에이를 위임 할 방법이 없습니다. AJAX 콘텐츠를로드 할 때 해당 라인을 다시 호출해야합니다. 가장 간단한 방법은 두 위치 (페이지로드시 및 AJAX 요청 success콜백) 에서 호출 할 수있는 별도의 명명 된 함수로 이동하는 것입니다 .

function initialiseColorbox() {
    $(".iframe").colorbox({
        iframe: true,
        width: "1000px",
        height: "500px"
    });
    $(".inline").colorbox({
        inline: true,
        width: "50%"
    });
    $(".callbacks").colorbox({
        onOpen: function () {
            alert('onOpen: colorbox is about to open');
        },
        onLoad: function () {
            alert('onLoad: colorbox has started to load the targeted content');
        },
        onComplete: function () {
            alert('onComplete: colorbox has displayed the loaded content');
        },
        onCleanup: function () {
            alert('onCleanup: colorbox has begun the close process');
        },
        onClosed: function () {
            alert('onClosed: colorbox has completely closed');
        }
    });
}

나를 위해 일한 해결책을 찾을 수 있기 전에 같은 문제가있었습니다. 그래서 미래의 누군가가 기회를 줄 수 있다면 내가 찾은 모든 솔루션이 이것보다 조금 더 복잡했기 때문에 그것이 옳은지 알려주십시오.

따라서 Tamer Durgun이 말했듯이 ajaxStop 내에 코드를 배치하므로 이벤트가 ajax에 의해 완료 될 때마다 코드가 복원됩니다.

$( document ).ajaxStop(function() {

//your code

}

Worked for me :)


            // EXAMPLE FOR JQUERY AJAX COMPLETE FUNC.
            $.ajax({
            // get a form template first
            url: "../FPFU/templates/yeni-workout-form.html",
            type: "get",
            success: function(data){
            // insert this template into your container
                $(".content").html(data);
            },
            error: function(){
                alert_fail.removeClass("gizle");
                alert_fail.addClass("goster");
                alert_fail.html("Template getirilemedi.");
            },
            complete: function(){
                // after all done you can manupulate here your new content
                // tinymce yükleme
                tinymce.init({
                    selector: '#workout-aciklama'
                });
            }

Your event handlers are being lost when you replace the content. When you set you hover events, jQuery is setting them on the events on the page currently. So when you replace them with ajax, the events are not associated with those elements because they are new.

To fix this you can either call the function that binds them again or you can instead set the event handler on the document as in this answer using $(document).on

That way the event is set on the document and any new elements will get the event called.


You can use jQuery ajax's complete function after retrieving data form somewhere, it will see updated elements after ajax complete


You Can User jQuery's delegate() method which Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.In my case it's working as expected

this $(selector).click(function(e){}

become this after Using delegate() method

$( "body" ).delegate( "selector", "click", function(e) {}

Hope this will help ;)


I'm late to the party but I would combine two of the answers. What worked for my specific needs was to incorporate the ajaxstop within the complete

 complete: function () {
          $( document ).ajaxStop(function() {
            //now that all have been added to the dom, you can put in some code for your needs.
            console.log($(".subareafilterActive").get().length)
           
          })
        }

ReferenceURL : https://stackoverflow.com/questions/16062899/jquery-doesnt-work-after-content-is-loaded-via-ajax

반응형