将equalheight函数移至functions.js后导入jQuery遇类型错误求助
Hey there! Let's break down why your equalHeight function is throwing that error after moving it to functions.js—it almost always boils down to how you're importing jQuery. Here's what's going on and how to fix it:
The Root Cause: Incorrect jQuery Import
Your line import {$} from 'jquery' is the culprit. jQuery exports itself as a default ES module, not a named export. When you try to destructure $ from the import, you're actually grabbing an undefined value (since there's no named export called $). When you then try to call $(selector), you're trying to invoke undefined as a function—hence the "Object(...) is not a function" error.
Fix 1: Correct the jQuery Import Statement
Replace your import line with the standard default import for jQuery:
import $ from 'jquery';
This will correctly assign the full jQuery function to the $ variable, just like it worked in your original eventslist.bundle.js file.
Fix 2: Verify the Import Works
To confirm jQuery is loading properly, add a quick console log right after the import:
import $ from 'jquery'; console.log($); // Should log the jQuery function object, not undefined
If this logs undefined, double-check:
- You have jQuery installed via npm/yarn (run
npm install jqueryif you haven't already) - Your jQuery version supports ES modules (jQuery 3.0+ does this natively)
- Your bundler (Webpack, Vite, etc.) is configured to handle ES modules correctly
Example Working Code
Here's how your functions.js should look with the fix:
import $ from 'jquery'; export function equalheight(selector) { let maxHeight = 0; // Reset heights first to avoid incorrect calculations $(selector).each(function() { $(this).height('auto'); }); // Find the tallest element $(selector).each(function() { const currentHeight = $(this).outerHeight(); if (currentHeight > maxHeight) { maxHeight = currentHeight; } }); // Apply the max height to all elements $(selector).height(maxHeight); }
Then in eventslist.bundle.js, import and use it as you intended:
import { equalheight } from './functions.js'; // Make sure to call it after the DOM is loaded $(document).ready(function() { equalheight('.your-target-elements'); // Replace with your actual selector });
Bonus: Edge Cases to Check
If you still run into issues, make sure:
- The selector you're passing to
equalheightactually matches elements in the DOM (an empty selector won't throw this error, but it won't do anything either) - You're not calling
equalheightbefore the DOM is fully loaded (hence the$(document).ready()wrapper)
内容的提问来源于stack exchange,提问作者Martyn

