【问题标题】:Razor Dropdown onchange event not firing always undefinedRazor Dropdown onchange 事件未触发始终未定义
【发布时间】:2015-03-05 21:21:35
【问题描述】:

我在剃刀视图中使用下拉列表助手

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

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

<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>

【问题讨论】:

  • box() 是一个与您显示的代码无关的函数 - 您的意思是 clickMe() 吗?您显示的代码工作正常。

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


【解决方案1】:

这不起作用的实际原因是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>

【讨论】:

    【解决方案2】:

    我更喜欢将点击事件放在脚本中。尝试删除您的 on change 事件并将您的功能 clickMe 替换为

    $(document).on('change', '#Country', function(){
        alert('made it!');
    });
    

    这会在下拉列表的 ID 上进行选择,我认为在呈现的下拉列表中将是国家/地区

    【讨论】:

      【解决方案3】:

      这是另一种选择:

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

      只需确保您提供下拉列表名称= 或 id=

      【讨论】:

      • 您有一个错字,第一个 CountryId 后缺少撇号。
      猜你喜欢
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多