jquery - 根据先前的选择使用 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 函数?
解决方案
第二个更改功能不起作用。
在这种情况下,您将在渲染期间创建的 2nd select
( )添加一个事件,但是,当您更改 1st 时,会出现以下代码:#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())
);
推荐阅读
- java - CompletableFuture 在完成时工作缓慢
- linux - Flatpak xdg-desktop-portal 中的 FileChooser 可以返回不是文件的 URI 吗?
- android - 显示键盘时按钮不可见
- vuejs2 - 如何使用“vee-validate”给目标“is-invalid”类?
- unity3d - 增加触摸区域的大小 - Unity
- fsm - NuSMV 中的交换指令
- javascript - IE11长时间运行脚本问题背后的原因是什么?
- codenameone - 发送邮件时,我无法从 Rest ful 中捕获错误
- c++ - 我如何成功地将我的 .h 文件实施到我的主 .cpp 文件中以使其正常运行,例如,es 将非常有帮助,谢谢
- java - 使用 Graphite 将自定义指标写入 InfluxDB