基于先前的选择,使用ajax更改选择选项

问题描述 投票:0回答:1

我正在尝试根据先前的选择内容来更新三个链接的国家->省->城市选择框。我的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')
                        );
                    }
                });
            });
        });

第二更改功能不起作用。我究竟做错了什么?是否可以调用两次change和ajax函数?

jquery ajax select dropdown onchange
1个回答
2
投票

第二更改功能不起作用。

在这种情况下,您要将事件添加到在渲染过程中创建的第二个select#person_province),但是,当您更改第一个select时,有以下代码:

$('#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())
);
© www.soinside.com 2019 - 2024. All rights reserved.