【问题标题】:Use geocomplete function after ajax event在ajax事件之后使用geocomplete函数
【发布时间】:2015-04-28 01:17:51
【问题描述】:

我有一个按钮,它添加了一个输入框,您可以在其中输入地址。对于地址,我使用的是geocomplete plugin。在所有不是用 ajax 生成的输入框中,geocomplete 工作。如果输入是由 ajax 生成的,则不会。

这是我生成输入框的代码:

$('.add-drop').on('click', function(){  
     $.ajax({
         url : '/ajax/get-location-input',
         success : function(data){   
            $('#additional-drop').append(data);
        } 
    }); 
});

这是我的地理完整代码:

$(".get-location").geocomplete({
    details : "form",
    types : ["geocode", "establishment"]
  }).bind("geocode:result", function(event, result){  
      console.log(result);
});

问题不在于班级。我试图做类似$(".get-location").on("geocomplete"... 的事情,但它不起作用。任何想法?谢谢

【问题讨论】:

  • 将地理完整代码放入success函数中

标签: javascript jquery ajax geocoding geocomplete


【解决方案1】:

AJAX 是异步的(异步 JavaScript 和 XML) 这意味着它可能在主代码完成处理后执行

$.ajax({
    url: '/ajax/get-location-input',
    success:function(data){   
        alert(data);
    } 
});

alert('Hi ');

在这种情况下,Hi 将首先发出警报,然后是 data。在您的情况下,输入甚至可能尚未生成,因此geolocation 代码将看不到它们

正确的代码:

$.ajax({
    url: '$('#additional-drop').append(data);',
    success:function(data){   
        $('#additional-drop').append(data);

        $(".get-location").geocomplete({
            details: "form",
            types: ["geocode", "establishment"]
        });

    } 
});

将在从服务器获取数据后运行代码


这是我推荐的方法:

(function () {

    $.fn.addGeolocation = function () { this.geocomplete({ details: "form", types: ["geocode", "establishment"] }).bind("geocode:result", function(e, a){ console.log(a); }); }

    $.get('/ajax/get-location-input', function (a) {
        $('#additional-drop').append(data);

        $(".get-location").addGeolocation();

    });

    /* You may or may not need this */
    window.onload = function () { $(".get-location").addGeolocation(); }

}());

【讨论】:

    猜你喜欢
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    相关资源
    最近更新 更多