首页 > 解决方案 > django模板调用js对象

问题描述

如何在 django 中执行此操作。

<body onload="main_(1);"> </body>.  

我用这个试过了。

{ load static }
<body>
  {% if true %}
    <script src="{% static 'main/js/main_index.js' %}" ></script>
    <script>
      main_(1);
    </script>
  {% endif %}
</body>

到目前为止没有运气。有没有更简单的方法。

标签: javascriptdjangoonload

解决方案


在您的if模板标签中:它True不是true.

尝试:

{ load static }
<body>
  {% if True %}
    <script src="{% static 'main/js/main_index.js' %}" ></script>
    <script>
      main_(1);
    </script>
  {% endif %}
</body>

或者:

{ load static }
<body onload="main_(1);">
    <script src="{% static 'main/js/main_index.js' %}" ></script>
</body>

确保文件main_index.js已加载到浏览器 devtools 的网络选项卡中

我希望这将有所帮助。


推荐阅读