MVC4视图未检测到JQuery

MVC4 view is not detecting JQuery

本文关键字:JQuery 检测 视图 MVC4      更新时间:2023-09-26

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

$(document).ready(function () {
    $('.test').change(function () {
        alert("1");            
    });
});
@Html.DropDownList("PropertyContent", ViewBag.PropertyList as List<SelectListItem>, new { @class="test"})

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

这里怎么了?

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

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

更多可能的错误:

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

$('.test').change(function () {//在这一部分上,u需要在测试中添加'.'

你忘了这是一节课。

您还可以使用以下代码。

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

工作FIDDLE演示

$(function () {
    $('#PropertyContent').change(function () {
        alert("1");
    });
});

在视图或布局中的某个位置添加以下行:

@Scripts.Render("~/bundles/jquery")

此外,您的选择器也不正确。您没有class="test"的HTML元素。

请改用$('#PropertyContent')

请按照其Id获取dropDownList,如下代码所示。我给你举了一个例子:http://jsfiddle.net/pzzQu/

$(document).ready(function () {
    $('#PropertyContent').change(function(){
        alert('1');
    });
});