javascript Django 和 jQuery 的困难(为什么 $ 在管理应用程序中未定义?)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4709298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:35:55  来源:igfitidea点击:

Difficulty with Django and jQuery (why is $ undefined in the admin app?)

javascriptpythondjango

提问by Nick Heiner

It's been a while since I worked with jQuery; I think I'm making a stupid mistake.

我已经有一段时间没有使用 jQuery 了;我想我犯了一个愚蠢的错误。

Here is a Django widget:

这是一个 Django 小部件:

class FooWidget(Widget):

    # ...

    class Media:
        js = ('js/foowidget.js',)

Here is the .js file:

这是 .js 文件:

alert("bar");

$(document).ready(function() {
  alert("omfg");
  $('.foo-widget').click(function() {
    alert("hi");
    return false;
  });
});

alert("foo");

The only alert()that fires is the first. Do I have a stupid syntax error or something?

唯一的alert()火是第一个。我有愚蠢的语法错误吗?

Also, if some other included script on the page redefines $(document).ready, do I have to worry about it? I'm guessing that subsequent definitions will override mine, so it's safer for subsequent definitions to do something like:

另外,如果页面上包含的其他一些脚本重新定义了$(document).ready,我是否需要担心?我猜后续定义将覆盖我的,因此后续定义执行以下操作更安全:

$(document).ready(function() {
    document.ready()
    // real stuff
});

jQuery is already included in the page by the time foowidget.jsis.

到时候 jQuery 已经包含在页面中了foowidget.js

Update: Based on @lazerscience's link, I tried the following instead, but it still fails just as before:

更新:基于@lazerscience 的链接,我尝试了以下操作,但它仍然像以前一样失败:

alert("bar");

$(function() {
  alert("omfg");
  $(".set-widget").click(function() {
    alert("hi");
    return false;
  });
});

alert("foo");

Update 2: Curiously, when I do:

更新 2:奇怪的是,当我这样做时:

alert($);

I get "undefined". This suggests that jQuery is actually not initialized. This confuses me, because the <head>includes:

我得到“未定义”。这表明 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>

Doesn't putting my script after the jQuery scripts ensure that $will be defined?

是否将我的脚本放在 jQuery 脚本之后确保$将被定义?

Update 3: from jquery.min.js:

更新 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? /* ... */

Looks correct to me.

对我来说看起来是正确的。

This is from the Firebug console:

这是来自 Firebug 控制台:

Error: $ is not a function
[Break On This Error] $(function() {
foowidget.js (line 5)
>>> $
anonymous()
>>> jQuery
undefined
>>> $('a')
null
>>> $(document)
null

Update 4: $is defined on all page of my Django site except the admin app. Odd...

更新 4$在我的 Django 站点的所有页面上定义,除了管理应用程序。奇怪的...

Update 5: This is interesting.

更新 5:这很有趣。

jQuery.init.js:

jQuery.init.js:

// Puts the included jQuery into our own namespace
var django = {
 "jQuery": jQuery.noConflict(true)
}; 

From the console:

从控制台:

>>> $
anonymous()
>>> django
Object {}
>>> django.jQuery
function()
>>> django.jQuery('a')
[a /admin/p..._change/, a /admin/logout/, a ../../, a ../, a.addlink add/]

采纳答案by Bernhard Vallant

You can use $(document).ready()as often as you want to on one page. It doesn't redefineanything as you call it, but the call of ready()adds functions that are called when "the document is ready". To debug your code eg. use Firebug that will show you more detailled information about where the error occurs if there's any!

您可以$(document).ready()在一页上随意使用。它不会在您调用它时重新定义任何内容,而是调用ready()add 函数,这些函数在“文档准备好”时调用。调试您的代码,例如。使用 Firebug,它会向您显示有关错误发生位置的更详细信息(如果有的话)!

回答by Nick Heiner

Adding this to the top of my .js file fixes it:

将此添加到我的 .js 文件顶部修复它:

var $ = django.jQuery;

I'm not sure how to remove the jquery.init.js file, given that my project doesn't contain any scripts that use $for something other than jQuery.

我不确定如何删除 jquery.init.js 文件,因为我的项目不包含任何$用于 jQuery 以外的脚本。

回答by jinni

i solved this problem on this way, you have to include jquery.init.js (often its jquery.init.js from admin) in this file add following lines:

我以这种方式解决了这个问题,你必须在这个文件中包含 jquery.init.js(通常是来自管理员的 jquery.init.js)添加以下几行:

var django = {
    "jQuery": jQuery.noConflict(true)
};
var jQuery = django.jQuery;
var $=jQuery;

and u have in whole workspace jquery and $. For better code looking i prefer create my own jquery init file in project.

你在整个工作区都有 jquery 和 $. 为了获得更好的代码,我更喜欢在项目中创建我自己的 jquery init 文件。

回答by polarblau

Use the Firebug or Web Inspector JS console and type $and/or jQuery. That's the simplest way to find out if the library has been loaded correctly. In the unlikely case, that only jQuery is defined, you can wrap your script into it's own scope:

使用 Firebug 或 Web Inspector JS 控制台并输入$和/或jQuery. 这是确定库是否已正确加载的最简单方法。在不太可能的情况下,只定义了 jQuery,您可以将脚本包装到它自己的作用域中:

(function($){
    // your code here…
})(jQuery);

If nothing is defined at the console, the problem is most likely with the file and I'd try AndiDog's approach to see if there's anything loaded at all.

如果控制台未定义任何内容,则问题很可能出在文件上,我会尝试使用 AndiDog 的方法来查看是否加载了任何内容。

回答by Nids Barthwal

In django one reason for this problem when you are using import_export plugin. In that case follow these steps -

在 Django 中,当您使用 import_export 插件时出现此问题的一个原因。在这种情况下,请按照以下步骤操作 -

  1. Create a folder under admin template directory named import_export (templates/admin/import_export)
  2. Create a file there named base.html (templates/admin/import_export/base.html)
  3. type the below code base.html file.

    {% extends "admin/import_export/base.html" %} {% load static %} {% block extrahead %} {{ block.super }} static/admin/js/vendor/jquery/jquery.js static/admin/js/jquery.init.js
    {% endblock %}

  1. 在 admin 模板目录下创建一个名为 import_export 的文件夹(templates/admin/import_export)
  2. 在那里创建一个名为 base.html 的文件(templates/admin/import_export/base.html)
  3. 键入以下代码 base.html 文件。

    {% extends "admin/import_export/base.html" %} {% load static %} {% block extrahead %} {{ block.super }} static/admin/js/vendor/jquery/jquery.js static/admin/ js/jquery.init.js
    {% endblock %}

回答by Evgeni Shudzel

I wrapped my js code to use jQuery:

我包装了我的 js 代码以使用 jQuery:

window.onload = function () {
    if (django.jQuery('body').hasClass('change-list')) {
        ....
    }
}

回答by AndiDog

In Firefox, view the source code of the page, then click the link "/media/js/jquery.min.js" to see whether it loaded. Most probably you're getting a 404 because you didn't define the media URL correctly.

在火狐浏览器中,查看页面源代码,然后点击链接“/media/js/jquery.min.js”查看是否加载。很可能您收到 404 是因为您没有正确定义媒体 URL。

You can also use the development server for this purpose, it will show you all requests and the HTTP status code returned.

您也可以为此目的使用开发服务器,它会向您显示所有请求和返回的 HTTP 状态代码。

回答by Teddy

You probably forgot to include {{ form.media }}in your template.

您可能忘记包含{{ form.media }}在您的模板中。