使用jQuery进行事件绑定

Event binding using jQuery

本文关键字:事件 绑定 jQuery 使用      更新时间:2023-09-26

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

$(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>

您正走在正确的轨道上,但需要对事件绑定进行一些更改

要将事件绑定到ajax之后填充的select元素,请使用以下方法。更改事件是可选择的。

$(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);
            }
        });
    });
});

考虑以下添加:

$('body').on("change", "#state", function () {
                       ^^^^^^^^