You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django模板中JS函数未定义问题求助:Uncaught ReferenceError

问题解决:Uncaught ReferenceError: myFunction is not defined

核心错误原因

你遇到的JS函数未定义错误,根源是base.html中script标签的属性拼写错误:把加载脚本的src属性写成了scr,导致浏览器无法正确读取static/js/script.js文件,自然找不到myFunction函数。

修复步骤

  1. 打开templates/base.html,找到头部的script标签:
    错误代码:

    <script type="text/javascript" scr="{% static 'js/script.js' %}"></script>
    

    将scr修正为正确的src:

    <script type="text/javascript" src="{% static 'js/script.js' %}"></script>
    
  2. (可选优化)规范脚本加载位置
    建议将JS脚本移到</body>标签之前,确保页面DOM元素加载完成后再加载脚本,避免后续可能出现的DOM操作错误:

    {% load static %}
    
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>{% block title %}{% endblock %}</title>
        <link rel="stylesheet" href="{% static 'css/style.css' %}" />
      </head>
      <body>
        <div class="nav-bar">
          <a href="{% url 'myapp:home' %}">Home</a> | 
          <a href="{% url 'myapp:about' %}">About Us</a> |
          <a href="{% url 'myapp:services' %}">Our Sevices</a> | 
          <a href="{% url 'myapp:info' %}">Info</a> |
        </div>
        <div class="page-content">
          {% block content %} 
          {% endblock %}
        </div>
        <div class="page-footer">
          <a href="#" >Usefull links</a> | 
          <a href="#" >Follow Us</a> |
          <a href="#" >Address</a> |
          <p  id="copyright">&copy; 2022 Learning Django</p>
        </div>
        <!-- 脚本移至此处 -->
        <script type="text/javascript" src="{% static 'js/script.js' %}"></script>
      </body>
    </html>
    

验证

修改完成后刷新页面,点击Click me!按钮,即可正常触发myFunction弹出提示框。

内容的提问来源于stack exchange,提问作者Racz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 03:30:53