JQuery - 将更改事件添加到Html.DropDownList

时间:2017-05-22 15:18:51

标签: javascript jquery html asp.net razor

抱歉,我是网络开发和ASP.Net的新手。当用户更改元素中的选定选项时,如何动态修改当前在浏览器中显示的HTML?

   <div class="form-group">
        @Html.LabelFor(model => model.CategoryId, "CategoryId", htmlAttributes: new { @class = "control-label col-md-2" })
         <div class="col-md-10">
              @Html.DropDownList("CategoryId", null, htmlAttributes: new { @class = "form-control" })
              @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
         </div>
     </div>

   <h1></h1>

    <script>
        $(function() {
            $('#CategoryId').on('change', function (e) {
                 var categoryId = this.value;

                 //do stuff to HTML based on selected value
                 if (parseInt(categoryId) === 3) {
                    $('h1').text('stuff');
                 }
             });
        });
    </script>

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。你需要在jquery中导入。

<div class="form-group">
    @Html.LabelFor(model => model.CategoryId, "Category", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("CategoryId", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
    </div>
</div>


<h1></h1>

<script type="text/javascript" src="/scripts/jquery-3.1.1.js"></script>

<script>
    $(function() {
        $('#CategoryId').on('change', function (e) {
            var categoryId = this.value;

            //do stuff to HTML based on selected value
            if (parseInt(categoryId) === 1) {
                $('h1').text('stuff');
            }
        });
    });
</script>