在文档准备好按国家 ID 获取城市时不起作用 [jquery 自定义插件]

On document ready get cities by country id not working [ jquery custom plugin ]

我制作了一个 jquery 插件来获取国家/地区更改时的城市下拉列表。

我希望在页面加载时更新表单时具有相同的功能。

我不想在文档准备好时重复我的代码我想重复使用我在更改事件中使用的代码。

为此创建了一个函数,并在文档就绪和更改事件中调用它。

调用函数 ajax 正在获取数据,但无法将其附加到城市下拉列表中

这是我在创建函数以在页面加载中重用之前的代码

此代码有效,但仅适用于国家/地区下拉列表的更改事件,但现在我希望它在页面加载时也从 ajax 加载城市

仅在国家/地区下拉列表发生变化时

$(document).ready(function () {

  (function ($) {
    //To Use getCities Function pass country drop down class selecter in parameter
    $.fn.getCities = function (countryClass) {
      $(document).on('change', countryClass, function () {
        var countryId = $(this).val();
        //Call Ajax to get cities by country id from ApplicationAjaxController's function getCitiesAction
        $.ajax({
          type: 'post',
          url: "{{ path('cms_application_city') }}",
          dataType: 'JSON',
          data: {
            countryId: countryId
          },
          success: function (res) {
            $('.CityName').css('display', 'none');
            if (res.success == 1) {
              var html = '';
              for (var key in res.cities) {
                var value = res.cities[key];
                html += '<option value="' + key + '">' + value + '</option>';
              }
              $("#ajax_citySelect").html(html);
              $("#ajax_citySelect").append('<option value="other">Other</option>');
              $("#ajax_citySelect").selectpicker('refresh');
              //Show and hide City Text field on changing city option
              $(document).on('change', '.citySelect', function () {
                if ($(this).val() == 'other') {
                  $('.CityName').css('display', 'block');
                } else {
                  $('.CityName').css('display', 'none');
                }
              });// end of city on change event
            } else {
              var html = '';
              html += '<option value="' + res.cities + '">' + res.cities + '</option>';
              $("#ajax_citySelect").html(html);
              $("#ajax_citySelect").append('<option value="other">Other</option>');
              $("#ajax_citySelect").selectpicker('refresh');
            }
          },
          error: function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus);
            if (jqXHR.status == 500) {
              alert('Internal error: ' + jqXHR.responseText);
            } else {
              alert('Unexpected error.');
            }
          }
        }); //end of ajax function
      });// end of country on change event
    };
  }(jQuery)); //end of plugin function

  $(".Country").getCities('.Country');
});

为了在页面加载上添加相同的功能,我制作了函数,这是我的代码

但它不起作用,谁能告诉我我做错了什么?

添加功能后在页面加载时重用

 $(document).ready(function () {
        function AjaxCallBack(response){
            return response;
        }
        function getCityByCountry(countryClass) {
            var $cityField = $(countryClass).parent().parent().next().find('select.citySelect');
            var $cityTextFieldContainer = $cityField.parent().parent();
            $cityTextFieldContainer.next().find('.city').parent().parent().css('display', 'none');
            $cityTextFieldContainer.next().find('.city').parent().parent().css('display', 'none');
            var countryId = $(countryClass).val();
            $.ajax({
                'async': false,
                type: 'post',
                url: "{{ path('cms_application_city') }}",
                dataType: 'JSON',
                data: {
                    countryId: countryId
                },
                success: function (res) {
                    AjaxCallBack(res);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.');
                    }
                }
            });
        }

        (function ($) {
            $.fn.getCities = function (countryClass) {
                $(document).ready(function () {
                    var getRes = getCityByCountry(countryClass);

                    console.log(getCityByCountry(countryClass));

                   var html = '';
                    if (getRes.success == 1) {

                        var city_id = res.city_id;
                        var selected = '';
                        for (var key in res.cities) {
                            var value = res.cities[key];
                            selected = '';
                            if (city_id == key) {
                                selected = 'selected';
                            }
                            html += '<option value="' + key + '" ' + selected + '>' + value + '</option>';
                        }

                        if (city_id == 0) {
                            selected = 'selected';
                        }

                        html += '<option value="0" ' + selected + '>Other</option>';
                        $cityField.html(html);
                        $cityField.selectpicker('refresh');
                        //Show and hide City Text field on changing city option
                        $(document).on('change', '.citySelect', function () {
                            if ($(this).val() == '0' || $(this).val() == 0) {
                                $cityTextFieldContainer.next().find('.city').parent().parent().css('display', 'block');
                            } else {
                                $cityTextFieldContainer.next().find('.city').parent().parent().css('display', 'none');
                            }
                        });
                    } else {
                        html += '<option value="' + res.cities + '">' + res.cities + '</option>';
                        html += '<option value="0" ' + selected + '>Other</option>';
                        $cityField.html(html);
                        $cityField.selectpicker('refresh');
                    }
                });
                $(document).on('change', countryClass, function () {
                    getCityByCountry(countryClass);
                });
            };
        }(jQuery));
        $(".Country").getCities('.Country');
    });

如果我对您的问题的理解正确,那实际上是一个非常简单的解决方法。调用处理 select 更改的代码后,只需触发更改事件即可。使用您发布的第一段代码,因为您知道这已经在加载文档后用于更改,然后在调用 .getCities()...

后添加这行额外的代码
$(".Country").trigger("change");

我只是通过在 document ready 上触发 change 事件来做到这一点并且它有效

$(".Country").trigger("change");