首页 > 解决方案 > 根据先前的选择使用 ajax 更改选择选项

问题描述

我正在尝试根据之前的选择更新三个链接的国家 -> 省 -> 城市选择框。我的 javascript 的第二部分不起作用

$(document).ready(function() {


            var $country = $('#person_country');
            var $province = $('#person_province');

            $country.change(function () {
                // ... retrieve the corresponding form.
                var $form = $(this).closest('form');
                var data = {};
                data[$country.attr('name')] = $country.val();
                // Submit data via AJAX to the form's action path.
                $.ajax({
                    url: $form.attr('action'),
                    type: $form.attr('method'),
                    data: data,
                    success: function (html) {
                        // Replace current field ...
                        $('#person_province').replaceWith(
                            // ... with the returned one from the AJAX response.
                            $(html).find('#person_province')
                        );
                    }
                });
            });


            $province.change(function () {
                // ... retrieve the corresponding form.
                var $form = $(this).closest('form');
                // Simulate form data, but only include the selected value.
                var data = {};
                data[$province.attr('name')] = $province.val();
                // Submit data via AJAX to the form's action path.
                $.ajax({
                    url: $form.attr('action'),
                    type: $form.attr('method'),
                    data: data,
                    success: function (html) {
                        $('#person_city').replaceWith(
                            // ... with the returned one from the AJAX response.
                            $(html).find('#person_city')
                        );
                    }
                });
            });
        });

第二个更改功能不起作用。我究竟做错了什么?有没有办法调用两次更改和 ajax 函数?

标签: jqueryajaxselectdropdownonchange

解决方案


第二个更改功能不起作用。

在这种情况下,您将在渲染期间创建的 2nd select( )添加一个事件,但是,当您更改 1st 时,会出现以下代码:#person_provinceselect

$('#person_province').replaceWith(
    $(html).find('#person_province')
);

这将删除select分配给它的现有和所有现有事件select

一种选择是使用事件委托:

$(document).on("change", "#person_province", function...

另一个选项是没有用.replaceWith,而是用新内容替换内容(或内部 HTML),这将select保持原样以及分配的事件。

在第一个select回调中,将其更改.replaceWith为:

$('#person_province').html(
    $(html).find("#person_province").html())
);

推荐阅读