简体   繁体   中英

How come my javascript doesn't work when I put my HTML in an “include”?

{% include "abc.html" %}

In Django, I put my html in this.

Now, my javascript won't work.

$(function(){
   alert('hi');
   $(".div_inside_abc").css("background","#000");

});

I even tried putting this javascript inside abc.html (at the top). It still won't work.

When I do:

$(".div_inside_abc").each(function(e){
    document.write($(this).attr("data-rel"));
});

I get this:

{{p.grid_image_ur l}}{{p.grid_image_ur l}}{{p.grid_image_ur l}}{{p.grid_image_ur l}}{{p.grid_image_ur l}}{{p.grid_image_ur l}}

That's not normal! It's as if Django's template is not rendering when I "include" something.

If you put JavaScript code inside HTML it won't execute (or be valid HTML). You have to wrap it in a SCRIPT tag if you're going to do it that way (which I don't advise) or as a DOM1 attribute.

If you want jQuery to run this function on load I'd suggest doing this in an externally referenced JavaScript file that's loaded after jQuery,

$(document).ready(function() {
    alert('hi');
    $(".div_inside_abc").css("background","#000");
});

Or adding it inline as,

<script language="javascript">
    $(document).ready(function() {
        alert('hi');
        $(".div_inside_abc").css("background","#000");
});
</script>

after the jQuery include.

If you want this to be evaluated arbitrarily I'd suggest invoking the function directly this way (if you need the scope)

(function(){
    alert('hi');
    $(".div_inside_abc").css("background","#000");

})();

In abc.html change {{p.grid_image_ur l}} to {{ p.grid_image_url }}. May not be it, but is a good start. The page must be throwing an error that for some reason you can't see.

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