MVC4视图没有检测到JQuery

San*_*ndy 7 javascript jquery asp.net-mvc-4

我有一个@ Html.DropDownList,它调用一个jquery函数.但它未能调用该函数.我试过了-

$(document).ready(function () {
    $('.test').change(function () {
        alert("1");            
    });
});

@Html.DropDownList("PropertyContent", ViewBag.PropertyList as List<SelectListItem>, new { @class="test"})
Run Code Online (Sandbox Code Playgroud)

function test() {
        alert("1");
    }

@Html.DropDownList("PropertyContent", ViewBag.PropertyList as List<SelectListItem>, new { onchange="test();"})


@Scripts.Render("~/bundles/jqueryval") is also included in the view
Run Code Online (Sandbox Code Playgroud)

这里有什么不对?

Ken*_*eth 4

您的 jQuery 选择器是错误的,请改用 id-selector:

$(document).ready(function () {
    $('#PropertyContent').change(function () {
        alert("1");            
    });
});
Run Code Online (Sandbox Code Playgroud)

还有一些可能的错误:

  • 页面中未引用 jQuery。要检查这一点,请打开 firebug、chrome 开发工具或 IE 开发工具并检查是否有任何错误
  • 一个常见的错误是在视图中包含 $(document).ready,并且仅在底部引用 jQuery。这将产生错误,因为此时$未知。可能的解决方案:
    1. 将代码移至外部文件并在 jQuery 包含后引用该文件
    2. 将 jQuery 声明移至 head 部分(不推荐,因为它会减慢页面加载速度)