级联下拉:检测代码所做的更改

时间:2014-07-23 19:56:28

标签: javascript jquery html asp.net-mvc drop-down-menu

在创建级联下拉菜单时遇到了问题。现在,第一个下拉列表有效:当我从第一个下拉列表中选择某个内容时,第二个下拉列表会相应地更改。但是,我需要在第二个下拉列表更改时触发另一个函数。我可以创建另一个.change函数,该函数在用户更改第二个下拉列表中的值时触发。但是,问题是没有检测到用户选择第一个下拉列表所触发的更改。换句话说,未检测到代码所做的更改。

我如何检测这两种类型的更改:代码所做的更改以及用户所做的更改? 或者,我如何从第二个下拉列表中获取第一个项目,以便将其传递给.change个函数共享的公共函数。

以下是我用来检测第一个下拉列表中的更改并填充第二个下拉列表的JavaScript函数。

    $(function () {

    $('#Country_ID').change(function () {
        debugger;
        var id = $("#Country_ID :selected").val();
        if (id != "") {

            $.ajax({

                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: '@Url.Action("CityList", "DropDown")',
                data: { "mCountry": id },
                dataType: "json",
                beforeSend: function () {
                    //alert(id);
                },
                success: function (data) {
                    var items = "";
                    $.each(data, function (i, city) {
                        items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
                    });
                    $('#City_ID').html(items);

                },
                error: function (result) {

                    alert('Service call failed: ' + result.status + ' Type :' + result.statusText);
                }
            });
        }
        else {
            var items = '<option value="">Select</option>';
            $('#City_ID').html(items);
        }

        @*I think I need to get the first value of the second dropdown here. 
          Then, pass the value to a function shared by the second `.change` function*@
    });
});

    $(function () {

        $('#Second_Dropdown').change(function () {
            @*call common function, passing selected value 
        });
    });

我对Javascript很陌生,所以越详细越好。

1 个答案:

答案 0 :(得分:1)

动态选择后,调用第二个下拉列表的.change()函数。 替换:

$('#City_ID').html(items)

使用:

$('#City_ID').html(items).change();