Program Club

jquery 클릭이 ajax 생성 콘텐츠에서 작동하지 않습니다.

proclub 2020. 10. 15. 21:58
반응형

jquery 클릭이 ajax 생성 콘텐츠에서 작동하지 않습니다.


나는 사용하고있다 $(".button").on("click", function(){ });

컨테이너에있는 버튼을 클릭하면 ajax 호출이 완료되고 콘텐츠가 새로운 내용으로 업데이트되고 클릭하려고하면 .button작동하지 않습니다. 버튼 을 클릭 해도 아무것도 반환되지 않습니다.

나는 심지어 시도했다

$(".button").live("click", function(){ });

또는

$(".button").click(function(){ });

어떻게 작동시킬 수 있습니까?

편집 : 내 HTML :

<div class="container">
   <ul>
       <li>item1</li>
       <li>item2</li>
       <li>item3</li>
   </ul>
   <input type="button" value="reload" class="button" />
</div>

이렇게해야합니다.

$('body').on('click', '.button', function (){
        alert('click!');
    });

ajax 요청 중에 변경되지 않는 컨테이너가있는 경우 이것이 더 성능이 좋습니다.

$('.container').on('click', '.button', function (){
        alert('click!');
    });

항상 동적 요소를 포함 할 가장 가까운 정적 요소에 대리자 이벤트를 바인딩합니다.


좋아, 하나의 매개 변수가 없기 때문에 .on () 함수를 올바르게 사용하여 문제를 해결했습니다.

대신에

$(".button").on("click", function() { } );

나는 사용했다

$(".container").on("click", ".button", function() { } );

대신에:

$(".button").on("click", function() { } );

나는 다음을 사용했다 :

$(".container").on("click", ".button", function() { } );

나는 이것을 사용했고 효과가 있었다.


이것이 당신이하려는 일입니까? $.on()부모에두고 있지만 .button작업을 위해를 선택합니다 .

.on (이벤트 [, 선택기] [, 데이터], 핸들러 (eventObject))

선택기 이벤트를 트리거하는 선택된 요소의 하위 항목을 필터링하는 선택기 문자열입니다. 선택기가 null이거나 생략 된 경우 이벤트는 선택한 요소에 도달 할 때 항상 트리거됩니다.

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

<div id="stuff">
    <button class="button">Click me!</button>
    <p>Stuff</p>
</div>

var $stuff = $('#stuff'),
    ajaxContent = $stuff.html();

$stuff.on('click', '.button', function(){
    $.get('/echo/html/', function(){
        $stuff.empty();
        console.log($stuff.html());
        alert($stuff.html()); // Look behind, #stuff is empty.
        $stuff.html(ajaxContent);
        console.log($stuff.html());
    });
});

http://jsfiddle.net/62uSU/1

또 다른 시연 :

var $stuff = $('#stuff'),
    ajaxContent = $stuff.html(),
    $ajaxContent,
    colors = ['blue','green','red'],
    color = 0;

$stuff.on('click', '.button', function(){
    $.get('/echo/html/', function(){
        color++;
        if (color == colors.length) color = 0;
        console.log($stuff.html());
        alert($stuff.html());
        $ajaxContent = $(ajaxContent);
        $stuff.append($ajaxContent).css('color', colors[color]);
        console.log($stuff.html());
    });
});

http://jsfiddle.net/62uSU/2/

참고 URL : https://stackoverflow.com/questions/9344306/jquery-click-doesnt-work-on-ajax-generated-content

반응형