如何使用JavaScript检查页面上元素的存在?
我在工作中遇到了一个问题,遇到了一个错误。
错误 : 错误图像
代码:
const open_menu = document.querySelector("#open-menu");
const close_menu = document.querySelector("#close-menu");
const nav_box = document.querySelector(".nav-box");
const eye_slash = document.querySelector(".fa-eye-slash");
const eye = document.querySelector(".fa-eye");
open_menu.addEventListener("click",function (){nav_box.classList.remove("off")});
close_menu.addEventListener("click",function (){nav_box.classList.add("off")});
eye_slash.addEventListener("click",function (){
document.querySelector("#password").type = "password";
});
const swiper = new Swiper('.swiper', {
direction: 'horizontal',
loop: true,
autoplay: {
delay: 4000,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
我想知道如何解决这个问题。因为我已经面对了很多问题。
I ran into a problem in my work and ran into an error.
error :
error image
code :
const open_menu = document.querySelector("#open-menu");
const close_menu = document.querySelector("#close-menu");
const nav_box = document.querySelector(".nav-box");
const eye_slash = document.querySelector(".fa-eye-slash");
const eye = document.querySelector(".fa-eye");
open_menu.addEventListener("click",function (){nav_box.classList.remove("off")});
close_menu.addEventListener("click",function (){nav_box.classList.add("off")});
eye_slash.addEventListener("click",function (){
document.querySelector("#password").type = "password";
});
const swiper = new Swiper('.swiper', {
direction: 'horizontal',
loop: true,
autoplay: {
delay: 4000,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
I want to know how to solve this problem. Because I have faced this problem a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当找不到元素时,
document.queryselector
将返回null。因此,您可以检查变量是否等于NULL。然后重复需要使用的每个元素。
或者,如果您使用的是javaScript的较新版本,则可以使用可选的链接。
缺点是,如果Open_Menu是 无效的。
When the element can't be found,
document.querySelector
will return null. So, you can check to see if the variable is equal to null.Then repeat that for each element you need to use.
Or, if you are using a newer version of JavaScript, you can use optional chaining.
The downside of that is that you can't do anything if open_menu is null.