[英]How to fix Uncaught TypeError: Cannot read property 'children' of null
carousel.js:5 未捕获的类型错误:无法读取 null 的属性“孩子”**
当我将 slider 广告到页面时出现此错误。
这是错误的js代码。
const track = document.querySelector('.carousel_track');
const slides = Array.from(track.children);
const dotsNav = document.querySelector('.carousel_nav');
const dots = Array.from(dotsNav.children); //here
const slideWidth = slides[0].getBoundingClientRect().width;
slides[0].style.left = 0;
slides[1].style.left = slideWidth + 'px';
谁能给我一个解决方案? 我真的很感谢你的帮助。
显然错误在这里抛出const dots = Array.from(dotsNav.children); //here
const dots = Array.from(dotsNav.children); //here
,虽然错误的来源来自上一行。 The error hints that the track is null, which can happen when the selector didn't return any value.
在没有看到您的 HTML 代码的情况下,不清楚确切的原因是什么,但很明显,在执行此代码时,DOM 中不存在带有 class carousel_nav
的元素。
调试步骤:
const dots = document.querySelector('.carousel_nav'); console.log('Dots are: ', dots); ...
然后在浏览器的控制台上检查值,它可能是 null。
检查 HTML 元素上的 class 是否正确写入,没有错别字和错误。 您甚至可以直接在浏览器控制台上运行 js 来查看代码是否真的在获取.carousel_nav
如果当您在浏览器的控制台中运行您的 js 代码并返回实际值而不是 null,但在页面加载时它仍然返回 null 那么这可能意味着轮播正在某个事件后由第三方库初始化,很可能是document.ready
,您还必须收听document ready
事件,然后才能执行您的代码。 有时仅等待document ready
是不够的,因此请检查您使用的库的文档,它应该有一些回调,您可以在轮播初始化后准确地执行代码。
可能是您使用的 carouself 库需要一个额外的参数来渲染点,您真的看到渲染的 dom 中的点吗?
如果您需要更多提示,请提供您正在使用的库名称以及 html
PS对不起,我没有看到//here
评论。 但是调试步骤是一样的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.