Razor Dropdown onchange事件未触发始终未定义

时间:2015-03-05 21:21:35

标签: javascript jquery asp.net-mvc asp.net-mvc-4 razor

我在剃须刀视图中使用dropdownlist帮助器

@Html.DropDownList("Country", null, "Select Your Country", new { @class = "form-control", onchange = "clickMe()" })

我已将我的jquery文件放在Layout.cshtml

的head部分
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Scripts.Render("~/bundles/jquery")
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>

但是当我把我的脚本放在剃刀视图中时

<script>
    $(document).ready(function () {
        function clickMe() { 
            alert();
        }
    });
</script>

它给出了引用错误:clickMe()未定义。 当我尝试此代码弹出警报以检查我的jquery文件是否已加载 这很好用

<script>
    $(document).ready(function () {
        alert();
    });
</script>

3 个答案:

答案 0 :(得分:4)

这不起作用的实际原因是Scoping。以下代码:

@Html.DropDownList("Country", 
  null, 
  "Select Your Country", 
  new { @class = "form-control", 
        onchange = "clickMe()" })

产生类似(我希望)的东西:

<select onchange="clickMe()">
// this is looking for a global `clickMe()` function
// but is it available?
</select>

我在这里注释了你的代码:

  // clickMe() is out of scope
  // it is not available here

  $(document).ready(function () 
  // start of anonymous function scope
  {

    function clickMe() 
    // start of clickme function scope
    { 
      alert();
    }
    // end of clickme function scope

    // clickMe() is available here
    // it was defined in this scope

  });
  // end of anonymous function scope

  // clickMe() is out of scope
  // it is not available here

</script>

我绝对不建议这样做,但要了解你如何使其工作可怕,你可以做以下

<script>
  $(document).ready(function () 
  {
    window.clickMe = function()
    { 
      alert();
    }
  });
</script>

通过将该功能分配给窗口对象,可以使其全局可用。

更好的方法,利用Matt Bodily's Answer可能看起来像:

<script>
    $(document).ready(function () {

        function clickMe() { 
            alert('made it!');
        }

        $(document).on('change', '#Country', clickMe );
    });
</script>

答案 1 :(得分:2)

我更喜欢将点击事件放在脚本中。尝试删除您的更改事件并使用

替换您的函数clickMe
$(document).on('change', '#Country', function(){
    alert('made it!');
});

这会选择我认为在呈现的下拉列表中属于国家/地区的下拉列表的ID

答案 2 :(得分:0)

这是另一种选择:

<script>
 $('#CountryID').change(function() {
    var value = $('#CountryID').val();


<script>

请确保您提供下拉名称=或id =

相关问题