jQuery - do something after an element is loaded via ajax, but not in the ajax function

StackOverflow https://stackoverflow.com/questions/3460858

  •  27-09-2019
  •  | 
  •  

문제

I'm trying to watch for an element to load on the page from an ajax call. I don't have access to the jquery that's making the ajax call. So, when some new html is loaded onto the page, I'd like to apply some changes to it.

I'm currently trying to use the .load() function:

$( '.autosuggest_keyword' ).load( 
    function()
    { 
        $( this ).val( 'load test' );
    }
);

Which isn't doing anything. I even tried making that a live binding, which doesn't really make sense, but I thought I'd give it a try.

The selector is correct.

Any ideas?

도움이 되었습니까?

해결책 5

I was able to get access to the original ajax call, so this question is moot now. I'm leaving it up for others to find, however, in case one of these answers helps them.

다른 팁

The .load() function expects an URL to which to send the AJAX request, fetch the data from the server and update the given element in the selector. So you need to pass an URL:

$('.autosuggest_keyword').load('/foo');

Do you know what is calling the inital ajax? if so you could call a function using the same event. Though this could cause some confusion if you're trying to change something that the ajax is loading.

Duck punching might be the answer:

should('duck-punch ajax success handler', function() {
    var origAjax = $.ajax;

    $.ajax = function(settings) {
        if(settings.url === 'the/request/page') {
            var origSuccess = settings.success;
            settings.success = function(responseHTML) {
                origSuccess.call(this, responseHTML);
                //apply some changes to html
            }

        }
        origAjax.call(this, settings);
    }
});

When you call .load, it's binding that event handler to elements that match your selector at the time you're calling it. Since the element is added after that, it's never bound. The .live function solves this problem by binding to currrent and future elements matching a selector. I think what you want is something like this (untested):

$( '.autosuggest_keyword' ).live('load', 
    function()
    { 
        $( this ).val( 'load test' );
    }
);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top