简体   繁体   中英

Javascript best way to handle binded element events in ajax loaded content

I have the following jquery ui automplete widget bind:

$(document).ready(function() {
    $('.zip-code-input').autocomplete({
        minLength: 2,
        source: function (request, response) {
            // Get list of zip codes 
        },
        select: function(event, ui) {
            // Do something with the selected item
        }
    });
});

Works fine for all zip code elements which are loaded on page request. Now i have to load a html form via ajax with a zip code input in it. Of course the autocomplete doesn't work. How can i handle it, without copy and past the same javascript code into the ajax loaded content?

You can do something like this:

function addAutoComplete(inputIdentifier){
   $(inputIdentifier).autocomplete({
     minLength: 2,
     source: function (request, response) {
        // Get list of zip codes 
    },
    select: function(event, ui) {
        // Do something with the selected item
    }
 });

Then after your HTML loads,

addAutoComplete(INPUT_IDENTIFIER);

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