关于下拉助手的变化?

on change in dropdown helper?

我正在使用枚举来显示像

这样的下拉菜单
  @Html.DropDownList("MyType",EnumHelper.GetSelectList(typeof(ImageType)),"Select My Type", new { @class = "form-control", onChange = "myFunction(this)" })

我想为此添加一个 onchange 函数,它接受两个参数,一个是当前元素 (this) 和下拉值

   onChange(this,value)

这应该给 select 标签,而 valu 应该是我 select 编辑的 我应该对我的帮手做些什么改变?

HTML 帮手:

 @Html.DropDownList("MyType",EnumHelper.GetSelectList(typeof(ImageType)),"Select My Type", new { @class = "form-control", onChange = "myFunction(this)" })

Javascript:

<script>
function myfunction(_this)
{
   var selectedValue = $(_this).val();
}
</script>

PS:您可以使用 _this 访问元素。 val() 将为您提供选定的值。

@Html.DropDownList("MyType") 创建一个 ID 为 MyTypeselect 元素。如果您正在使用 jQuery,您可以像这样添加一个更改事件处理程序。

<script>
    $(function(){
        $("#MyType").change(function(){
            console.log($(this).val());
            console.log(this);
        });
    });
</script>

如果您不使用 jQuery,则

<script>
    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById("MyType").addEventListener("change", function () {
            alert(this.value);
            console.log(this);
        });
    });
</script>

您可以通过 onChange 实现此目的,但您应该遵循 Unobtrusive JavaScript 方法