技术求助:页面出现Uncaught ReferenceError: $ is not defined错误
That error pops up because your component.js script is trying to use jQuery's $ alias, but jQuery hasn't been loaded by the browser yet when it runs your script. Let's break down how to fix this:
Step 1: Make Sure jQuery is Loaded Before Your Script
Looking at your update.html template, you're loading your custom script first, but there's no sign of jQuery being included anywhere. You need to add jQuery before your component.js file.
You have two options here:
- Add jQuery to your base template: If you use jQuery across your site, add it in
base.html(preferably right before the closing</body>tag) so it loads once for all pages:
Or if you're using a local copy of jQuery in your static files:<!-- Place this in base.html, before any other scripts --> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script><script src="{% static 'path/to/jquery.min.js' %}"></script> - Load jQuery directly in update.html: If you only need it for this page, add it right above your custom script:
{% extends 'base.html' %} {% block content %} {% load static %} <!-- Load jQuery first --> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <!-- Then load your component script --> <script src="{% static 'component/js/component.js' %}"></script> <h2>Create new component</h2> {% include 'snippets/form-snippet.html' with form=form %} {% endblock %}
Step 2: Wrap Your jQuery Code in a DOM Ready Handler
Even if jQuery loads first, if your script runs before the page's DOM is fully loaded, you might still run into issues. To prevent this, wrap all your jQuery code in a DOM ready function in component.js:
// Using the full DOM ready syntax $(document).ready(function() { // All your jQuery code goes here // Example: $('#some-element').doSomething(); }); // Or the shorter, common shorthand $(function() { // Your code here });
That should resolve the $ is not defined error—you're making sure jQuery exists when your script tries to use it, and that the DOM is ready for your code to manipulate elements.
内容的提问来源于stack exchange,提问作者arne

