javascript 的函数 'on change' 在 asp.net mvc 中不工作

Function 'on change' of javascript not working in asp.net mvc

我尝试使用 js ASP.NET MVC 5 查看基于类别的产品列表。我是新手,它根本不会作用于 select 框。这是我的代码:

我的Select块:

<select class="SelectCategory" name="SelectCategory">
<option value="0">All</option>
@foreach (var item in ViewBag.categories)
{
    if (ViewBag.SelectedCat == item.Value)
    {
        <option selected="selected" value="@item.Value">@item.Text</option>
    }
    else
    {
        <option value="@item.Value">@item.Text</option>
    }
}

Js:

@section Scripts {
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<script>

    $(function () {

        $("#SelectCategory").on("change",
            function() {
                var url = $(this).val();
                if (url) {
                    window.location = "/admin/shop/Products?catId=" + url;
                }

                return false;
            });
});

</script>
}

$("#SelectCategory").on("change",

这是错误的,因为您的元素不包含 ID 元素,而 ID 元素是 jQuery 选择器中 # 符号所表示的。

如果你想通过 name 属性定位元素,你应该使用以下:

$("[name='SelectCategory']").on("change",

$("#SelectCategory") 这将查找带有 ID 的 dom,但您已经使用了 class 和名称。您可以将 id 属性添加到 select

<select id='SelectCategory' class="SelectCategory" name="SelectCategory">