移动端轮播报错:Uncaught TypeError: Cannot read property '0' of undefined
changedTouches[0].pageX Hey there! Let's break down why you're hitting this error in your custom mobile carousel and how to fix it.
What's causing the error?
The message means you're trying to access the first element of the changedTouches array, but changedTouches itself is undefined. This usually happens for two common reasons:
- You're triggering this code with a non-touch event (like
clickormousemove)—those events don't have thechangedTouchesproperty built in. - The event object your handler receives has lost or never had the
changedTouchesproperty (maybe it was modified by other code, or you didn't pass the event correctly to your function).
Step-by-step fixes
Here are concrete ways to resolve this issue:
Ensure you're using proper touch events
Your carousel's touch logic should only run on dedicated touch events:touchstart,touchmove, andtouchend. Double-check your event bindings are targeting these, not mouse events. For example (in jQuery):// Correct: binding to a touch event $('.carousel-wrapper').on('touchend', function(e) { // Your touch handling code goes here }); // Wrong: click events don't have changedTouches! $('.carousel-wrapper').on('click', function(e) { // This will throw the error if you try to access e.changedTouches });Add safety checks before accessing
changedTouches[0]
Even with the right events, it's smart to verifychangedTouchesexists and has entries before accessing its index. This prevents the error from firing even if something unexpected happens:function handleTouchEnd(e) { // Check if changedTouches is present and has at least one entry if (e.changedTouches && e.changedTouches.length > 0) { const endX = e.changedTouches[0].pageX; // Proceed with your carousel swipe logic here } else { // Optional: Fallback for non-touch environments const endX = e.clientX || 0; // Or log a debug warning console.warn('No touch data available for this event'); } }For modern browsers, you can use the optional chain operator (
?.) for a cleaner check:const endX = e.changedTouches?.[0]?.pageX || e.clientX || 0;Verify the event object is intact
If the above fixes don't work, addconsole.log(e)at the start of your event handler to inspect the event object. Check ifchangedTouchesshows up in the logged output. If it's missing, there might be other code modifying or suppressing the event before your handler runs.
Bonus: Add touch/mouse compatibility
Since you're building a carousel, you might want to support both touch and mouse interactions. Here's a quick pattern to handle both without errors:
function handleSwipeEnd(e) { // Get the end X position, regardless of touch or mouse input const endX = e.changedTouches?.[0]?.pageX || e.clientX; // Your swipe logic here } // Bind to both touch and mouse events $('.carousel-wrapper') .on('touchend', handleSwipeEnd) .on('mouseup', handleSwipeEnd);
内容的提问来源于stack exchange,提问作者Daniel Andrade

