gpt4 book ai didi

javascript - 使用 jQuery 进行事件绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 10:31:09 25 4
gpt4 key购买 nike

我正在尝试根据所选的州显示城市选项,其中州是根据所选的国家/地区动态加载的(国家/地区列表是静态的)。但问题是我的操作页面从ajax接收数据没有接收任何状态值。这是我第一次尝试事件绑定(bind),所以请帮忙。

$(document).ready(function() {
$('#country').change(function() {
var value = $(this).val();
$.ajax({
url: "state_selector_db.php",
method: "post",
data: {
"country": value
},
success: function(result) {
var obj = jQuery.parseJSON(result)
$('div#state').html(obj.state);
}
});
});
$('body').on("change", function() {
var value2 = $(this).val();
$.ajax({
url: "state_selector_db.php",
method: "post",
data: {
"state": value2
},
success: function(res) {
var obj2 = jQuery.parseJSON(res)
$('div#city').html(obj2.city);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><b>Country:&nbsp</b>
</p>
<select id="country">
<option value="na">Select</option>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="england">England</option>
</select>
<div id="state"></div>
<div id="city"></div>

最佳答案

您的方向是正确的,但您需要对事件绑定(bind)进行一些更改

要将事件绑定(bind)到选择您在 ajax 之后填充的元素,请使用以下内容。更改事件是选择的。

$(document).ready(function () {
$('body').on("change", "div#state select", function () {
var value2 = $(this).val();
$.ajax({
url: "state_selector_db.php",
method: "post",
data: {
"state": value2
},
success: function (res) {
var obj2 = jQuery.parseJSON(res)
$('div#city').html(obj2.city);
}
});
});
});

关于javascript - 使用 jQuery 进行事件绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29209514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com