我已经有一段时间没有使用 jQuery 了;我想我犯了一个愚蠢的错误。
这是一个 Django 小部件:
class FooWidget(Widget):
# ...
class Media:
js = ('js/foowidget.js',)
这是 .js 文件:
alert("bar");
$(document).ready(function() {
alert("omfg");
$('.foo-widget').click(function() {
alert("hi");
return false;
});
});
alert("foo");
唯一alert()
那个火是第一个。我有愚蠢的语法错误还是什么?
此外,如果页面上包含的其他一些脚本重新定义了 $(document).ready
,我需要担心吗?我猜后续定义会覆盖我的,所以后续定义做这样的事情会更安全:
$(document).ready(function() {
document.ready()
// real stuff
});
jQuery 已包含在页面中 foowidget.js
是。
更新:根据@lazerscience 的链接,我尝试了以下方法,但仍然像以前一样失败:
alert("bar");
$(function() {
alert("omfg");
$(".set-widget").click(function() {
alert("hi");
return false;
});
});
alert("foo");
更新 2:奇怪的是,当我这样做时:
alert($);
我得到“未定义”。这表明 jQuery 实际上没有被初始化。这让我很困惑,因为 <head>
包括:
<script type="text/javascript" src="/media/js/jquery.min.js"></script>
<script type="text/javascript" src="/media/js/jquery.init.js"></script>
<script type="text/javascript" src="/media/js/actions.min.js"></script>
<script type="text/javascript" src="/static/js/foowidget.js"></script>
不将我的脚本放在 jQuery 脚本之后确保 $
会被定义吗?
更新 3:来自 jquery.min.js:
/*!
* jQuery JavaScript Library v1.4.2
* http://jquery.com/
*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Sat Feb 13 22:33:48 2010 -0500
*/
(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i? /* ... */
在我看来是正确的。
这是来自 Firebug 控制台:
Error: $ is not a function
[Break On This Error] $(function() {
foowidget.js (line 5)
>>> $
anonymous()
>>> jQuery
undefined
>>> $('a')
null
>>> $(document)
null
更新 4:$
在我的 Django 站点的所有页面上定义,除了管理应用程序。奇怪的...
更新 5:这很有趣。
jQuery.init.js:
// Puts the included jQuery into our own namespace
var django = {
"jQuery": jQuery.noConflict(true)
};
从控制台:
>>> $
anonymous()
>>> django
Object {}
>>> django.jQuery
function()
>>> django.jQuery('a')
[a /admin/p..._change/, a /admin/logout/, a ../../, a ../, a.addlink add/]
最佳答案
将它添加到我的 .js 文件的顶部修复它:
var $ = django.jQuery;
我不确定如何删除 jquery.init.js 文件,因为我的项目不包含任何将 $
用于 jQuery 之外的脚本。
关于javascript - Django 和 jQuery 的困难(为什么 $ 在管理应用程序中未定义?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4709298/