Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从@Html.DropDownListFor获取selectedIndex_Javascript_Asp.net Mvc - Fatal编程技术网

Javascript 从@Html.DropDownListFor获取selectedIndex

Javascript 从@Html.DropDownListFor获取selectedIndex,javascript,asp.net-mvc,Javascript,Asp.net Mvc,我需要一些帮助来使用JavaScript获取下拉列表的选定索引 这是我的Javascript代码: <script type="text/javascript"> $(function () { $("#test").change(function () { var index = document.getElementById('test').selectedIndex; alert(index); }); }); $(函数(

我需要一些帮助来使用JavaScript获取下拉列表的选定索引

这是我的Javascript代码:

<script type="text/javascript">

$(function () {
    $("#test").change(function () {
        var index = document.getElementById('test').selectedIndex;
        alert(index);
    });

});

$(函数(){
$(“#测试”)。更改(函数(){
var index=document.getElementById('test')。selectedIndex;
警报(索引);
});
});

下面是下拉列表:

<div class="editor-field" id="test">
                            @Html.DropDownListFor(x => x.TestID, new SelectList(Model.Tests, "TestID", "TestName"))
                            @Html.ValidationMessageFor(model => model.TestID)
                        </div>

@DropDownListFor(x=>x.TestID,新选择列表(Model.Tests,“TestID”,“TestName”))
@Html.ValidationMessageFor(model=>model.TestID)
更改下拉列表时,我总是“未定义”。
有人有办法解决这个问题吗?

当调用事件的处理程序时,jQuery将
这个
设置为目标元素。然后,您可以使用它来获取目标元素内部的
所选
选项的索引

$("select", "#test").change(function () {
    var index = $("option:selected", $(this)).index()
    alert(index);
});

仅供参考
test
是一个
div
。谢谢。@DanielA.White,没关系。它根据上下文进行选择。
#test
不应触发更改事件,或者不保证。@DanielA.White,很好。再次修复了上下文。