jQuery not recognized in extended html python flask

霸气de小男生 提交于 2021-02-17 05:51:10

问题


Not sure what is going on here. It seems that jQuery is not "extended" from a base.html file to an external one.

I have:

#base.html

<!doctype html>
<html class="no-js" lang="en">

<head>
...
... # css imports
</head>

<body>

   # some fixed stuff

   {% block body %}

      # some stuff specific to base.html

   {% endblock %}

   # js imports at the end of the body

   <script src="static/js/jquery-3.1.0.min.js"></script>

    ... # various other js
</body>
</html>

Then I have another html file:

#test.html

{% extends "base.html" %}

{% block body %}

    # some stuff

   <script type="text/javascript">

        $(document).ready( function () {
             alert("foo")
         } );

    </script>

{% endblock %}

Now, I don't get any alert. However, if I use plain javascript it works as expected.

I noticed that if I import again jQuery in test.html, jQuery works fine. But what's the point of extending then?

There must be something that I'm missing. By the way, this seems to happen only with jQuery, all other javascript libraries seem to be extended fine.


回答1:


It's really very simple. When the following code runs, it needs to run using jQuery.

<script type="text/javascript">

    $(document).ready( function () {
         alert("foo")
     } );

</script>

However, your jQuery is being loaded AFTER these commands, whereas, it needs to be placed BEFORE that.

It's like you're drinking water from a glass before you're putting water in it. You need to put the water in the glass first and then drink it. I don't know if this example makes it easy or not.




回答2:


Add this line.I hope this will work.

<script type="text/javascript" src="{{ url_for('static', filename='js/jquery-3.1.0.min.js') 
}}"></script>



回答3:


At the moment $(document).ready( function () { executes, $ hasn't been aliased to jQuery, which has yet to load.



来源:https://stackoverflow.com/questions/53511651/jquery-not-recognized-in-extended-html-python-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!