我正在尝试根据先前的选择内容来更新三个链接的国家->省->城市选择框。我的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函数?
第二更改功能不起作用。
在这种情况下,您要将事件添加到在渲染过程中创建的第二个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())
);