programing

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

nicescript 2023. 4. 2. 13:28
반응형

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「」를 .id의 of의 click동적 것을 DOM일 입니다).<div>페이지 내용을 모두 포함하는 페이지)를 클릭하면 효율이 약간 향상됩니다.

이 다룰 필요가 때 합니다..hover()hover를 jQuery에 위한 합니다.mouseenter ★★★★★★★★★★★★★★★★★」mouseleave 위임을 , 이벤트 위임할 수 있습니다.

$(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 (컬러박스) 또ququ jQuery ( color box 。후 은 이러한 입니다(시및 요청 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이 말했듯이, 우리는 또한 당신의 코드를 ajax Stop에 넣을 것입니다.따라서 당신의 코드는 ajax에 의해 어떤 이벤트가 완료될 때마다 복구됩니다.

$( document ).ajaxStop(function() {

//your code

}

나를 위해 일했어 :)

// 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'
        });
    }

콘텐츠를 바꾸면 이벤트 핸들러가 손실됩니다.했을 때hover이벤트, jQuery가 현재 페이지의 이벤트에 이벤트를 설정하고 있습니다.따라서 이러한 요소를 ajax로 대체하면 이벤트가 새 요소이기 때문에 해당 요소와 연관되지 않습니다.

이 문제를 해결하려면 이들을 바인딩하는 함수를 다시 호출하거나 $(문서)를 사용하여 이 답변에서와 같이 문서에 이벤트 핸들러를 설정할 수 있습니다.

이렇게 하면 문서에 이벤트가 설정되고 새 요소가 이벤트를 호출합니다.

jQuery의 delegate() 메서드는 특정 루트 요소 세트를 기반으로 현재 또는 미래에 셀렉터와 일치하는 모든 요소의 하나 이상의 이벤트에 핸들러를 연결할 수 있습니다.저 같은 경우에는 예상대로 동작하고 있습니다.

★★★★★★★★★★★★★★★★★」$(selector).click(function(e){}

delegate() 메서드를 사용한 후 이 상태가 됩니다.

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

이것이 도움이 되기를 바란다;)

어딘가에서 데이터 형식을 검색한 후 jQuery ajax의 complete 함수를 사용할 수 있습니다. ajax 완료 후 업데이트된 요소가 표시됩니다.

이건 나한테 효과가 있었어

다음 대신:

$(document).ready(function(){
//code
});

나는 했다:

$(document).on('mouseenter', function(){
//code
});

나는 파티에 늦었지만 두 가지 답을 조합하고 싶다.내 특정 요구에 효과가 있었던 것은 아약스톱을 완성도 안에 포함시키는 것이었다.

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)

     })
}

그냥 대안일 뿐이야.

$(window).on('load', _ => {
    // some jQuery code ..
})

그러면 위임된 핸들러가 창에 바인딩됩니다.창이 완전히 로드되면 DOM뿐만 아니라 모든 그래픽/포함/훅/요구를 포함하여 실행됩니다.

$(document).ready(_ => ... AJAX, AJAX, DOM 에 되지 않는, 유지합니다.특정 요소를 @Anthony Grist에서 설명한 대로 정의하여 함수 또는 이벤트가 완전히 로드되었을 때 실행하거나 위와 같이 부하 이벤트를 창에 바인딩할 수 있습니다.

https://api.jquery.com/load-event/
https://api.jquery.com/on/ #syslogs-data-syslogs

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

반응형