$没有定义 - asp.net MVC 4 [英] $ is not defined - asp.net MVC 4
问题描述
有了这个code以下,我得到一个错误: $没有定义
。我的问题是:怎么可能?
With this code below, I get an error: $ is not defined
. My question is: How it is possible?
...
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#cb').click(function () {
if (this.checked) {
$('div#div').slideDown();
} else {
$('div#div').slideUp();
}
});
})
});
</script>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
@Scripts.Render("~/Scripts/jquery-1.7.1.min.js")
@Scripts.Render("~/Scripts/jquery-ui-1.8.20.min.js")
我们可以看到,它正确加载所有的脚本:
As we can see, it load properly all of scripts:
<script src="/Scripts/jquery-1.7.1.min.js"></script>
<script src="/Scripts/jquery-ui-1.8.20.min.js"></script>
<script src="/Scripts/jquery-1.7.1.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
如何解决?
推荐答案
您已经放在你的脚本在视图体内,而不是脚本里面
部分,它是它属于和在引用jQuery的:
You've placed your script in the view body and not inside the Scripts
section which is where it belongs and after referencing jQuery:
@section Scripts {
@Scripts.Render("~/Scripts/jquery-1.7.1.min.js")
@Scripts.Render("~/Scripts/jquery-ui-1.8.20.min.js")
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
$('#cb').click(function () {
if (this.checked) {
$('div#div').slideDown();
} else {
$('div#div').slideUp();
}
});
});
</script>
}
另外要避免引用jQuery的两倍(如你的情况)仔细检查,如果您还没有它已经作为一个捆绑你的 _layout
。
和最后一句话:因为默认情况下,脚本都包含在DOM年底,就在结束标记之前,你并不需要在包装脚本中的的$(document) 。就绪
只是因为它执行DOM的时候就已经被加载。因为你有两次你的code更是雪上加霜。请记住, $(函数(){...});
等同于 $(文件)。就绪(函数(){。 ..});
和你的情况你的那些东西嵌套2,当你其实并不需要任何人
And one last remark: since by default scripts are included at the end of the DOM, just before the closing body tag, you don't need to be wrapping your script in a $(document).ready
simply because by the time it executes the DOM will already be loaded. Your code is even worse because you had it twice. Bear in mind that $(function() { ... });
is equivalent to $(document).ready(function() { ... });
and in your case you've nested 2 of those things when you actually don't need any of them.
所以:
@section Scripts {
@Scripts.Render("~/Scripts/jquery-1.7.1.min.js")
@Scripts.Render("~/Scripts/jquery-ui-1.8.20.min.js")
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$('#cb').click(function () {
if (this.checked) {
$('div#div').slideDown();
} else {
$('div#div').slideUp();
}
});
</script>
}
这篇关于$没有定义 - asp.net MVC 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!