问题描述
我正在尝试使用 jQuery 设置 cookie:
I am trying to set a cookie using jQuery:
$.cookie("testCookie", "hello");
alert($.cookie("testCookie"));
但是当我加载我的页面时,我收到错误$.cookie is not a function".以下是我所知道的:
But when I load my page, I receive the error "$.cookie is not a function". Here is what I know:
- 我已经在这里下载了 jQuery cookie 插件.
- 我正在链接到 jQuery,然后是 cookie 插件.
- jQuery 和 jQuery.cookie 均以 200 OK 正确加载.
- I have downloaded the jQuery cookie plugin here.
- I am linking to jQuery and THEN the cookie plugin.
- Both jQuery and jQuery.cookie are loading correctly with 200 OKs.
我查看了其他几个答案(此处和此处 等),大多数人建议将 cookie.js 文件重命名为该文件.我已将我的 cookie 文件重命名为jquery.cookeee.js",但结果是一样的.
I have looked at several other answers (here and here among others), to which most people suggested renaming the cookie.js file. I have renamed my cookie file "jquery.cookeee.js" but the results are the same.
对这里发生的事情有什么想法吗?
Any ideas on what is going on here?
如果有帮助,我将在 MVC 4 中创建一个 Web 应用程序.
If it helps, I am creating a web application in MVC 4.
推荐答案
以下是我遇到的所有可能的问题/解决方案:
Here are all the possible problems/solutions I have come across:
$.cookie
不是标准的 jQuery 函数,需要下载插件 这里.确保在必要时包含适当的 标记(见下文).
$.cookie
is not a standard jQuery function and the plugin needs to be downloaded here. Make sure to include the appropriate <script>
tag where necessary (see next).
当包含 cookie 脚本时,确保首先包含 jQuery,然后是 cookie 插件.
When including the cookie script, make sure to include jQuery FIRST, then the cookie plugin.
<script src="~/Scripts/jquery-2.0.3.js" type="text/javascript"></script>
<script src="~/Scripts/jquery_cookie.js" type="text/javascript"></script>
3.不要多次包含 jQuery
这是我的问题.确保您不会多次包含 jQuery.如果是,则可能是:
3. Don't include jQuery more than once
This was my problem. Make sure you aren't including jQuery more than once. If you are, it is possible that:
- jQuery 加载正确.
- cookie 插件加载正确.
- 您第二次加入 jQuery 会覆盖第一个并破坏 cookie 插件.
对于使用 ASP.Net MVC 项目的任何人,请注意默认的 javascript 包包含.我第二次加入 jQuery 是在我的全局布局页面之一的 @Scripts.Render("~/bundles/jquery")
下.
For anyone using ASP.Net MVC projects, be careful with the default javascript bundle inclusions. My second inclusion of jQuery was within one of my global layout pages under the line @Scripts.Render("~/bundles/jquery")
.
在极少数情况下,将文件重命名为不包含.cookie"的内容已修复此错误,这显然是由于网络服务器问题.默认情况下,下载的脚本名为jquery.cookie.js",但尝试将其重命名为jquery_cookie.js",如上所示.有关此问题的更多详细信息,请参见此处.
In some rare cases, renaming the file to something that does NOT include ".cookie" has fixed this error, apparently due to web server issues. By default, the downloaded script is titled "jquery.cookie.js" but try renaming it to something like "jquery_cookie.js" as shown above. More details on this problem are here.
这篇关于jQuery $.cookie 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!