繁体   English   中英

MVC4视图没有检测到JQuery

[英]MVC4 view is not detecting JQuery

我有一个@ 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-selector代替:

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

还有一些可能的错误:

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

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

你忘了它是一堂课。

您还可以使用以下代码。

$(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');
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM