简体   繁体   中英

Using jquery to run code when django document is ready

I am building a django admin site and am using javascript and jquery (2.0.3) to add some extra functionality to the forms.

I am importing the scripts into my page like this:

<html>
    <head>
        <script type="text/javascript" src="/static/admin/js/jquery.js"></script>
        <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
        <script type="text/javascript" src="/static/project/js/project.js"></script>
    </head>
    <!-- ... -->
</html>

At first I placed the following code at the end of project.js :

function tryCustomiseForm() {
    // ...
}

$(document).ready(tryCustomiseForm); 

Unfortunately this results in an Uncaught TypeError: undefined is not a function exception on the last line.

I then tried the alternative syntaxes of ready() without any more luck.

Lastly I explored the change_form.html template and found this inline javascript:

<script type="text/javascript">
    (function($) {
        $(document).ready(function() {
            $('form#{{ opts.model_name }}_form :input:visible:enabled:first').focus()
        });
    })(django.jQuery);
</script>

I was able to modify it to suit my needs and now my project.js ends with:

(function($) {
    $(document).ready(function() {
        tryCustomiseForm();
    });
})(django.jQuery);

While this results in the correct behaviour I don't understand it .

This leads to my question: Why did my first approach fail? And what is the second approach doing?

It's hard to tell from the code you've posted, but it looks like the $ variable is not assigned to jQuery in your template; hence the $() construct threw the undefined function error.

The reason the latter works is because it puts a closure around your DOMReady handler, which passes in django.jQuery , which I assume to be the noConflict jQuery assigned variable from your template, and assigns it to the $ within the scope of that:

(function($) { // < start of closure
    // within this block, $ = django.jQuery
    $(document).ready(function() {
        tryCustomiseForm();
    });
})(django.jQuery); // passes django.jQuery as parameter to closure block

Django文档解释了这一点 :jQuery是命名空间,因此您可以使用django.jQuery在管理模板中引用它。

try

$(document).ready(function(){

 tryCustomiseForm();

}); 

function tryCustomiseForm() {
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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