简体   繁体   English

Javascript处理Ajax加载内容中绑定元素事件的最佳方法

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

I have the following jquery ui automplete widget bind: 我有以下jquery ui automplete小部件绑定:

$(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. 现在,我必须通过ajax加载带有zip码输入的html表单。 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? 我如何处理它,而无需将相同的javascript代码复制并粘贴到ajax加载的内容中?

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, 然后,在加载HTML之后,

addAutoComplete(INPUT_IDENTIFIER);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM