javascript - 无法删除类列表
问题描述
我正在尝试删除active
在我的代码中调用的类。active
当使用单击元素时会出现该类,addEventListener
但我想使用一个onClick
搜索该类active
并将其删除的函数。单击另一个元素时仍然允许addEventListener
添加。active
这是我想要实现的一个示例,在移动设备中我想做多层次,其中 div 堆叠在另一个 div 的顶部,并且可以返回到以前的 div https://codyhouse.co/demo/mega-下拉/index.html#0
const dropDowns = document.querySelectorAll(".mobile-nav .dropdown");
for (var i = 0; i < dropDowns.length; i++) {
dropDowns[i].addEventListener("click", function() {
this.children[1].classList.add("active");
});
}
function closeDropDown() {
const temp = document.querySelectorAll(".mobile-nav .dropdown-content");
temp.classList.remove("active");
}
<div class="dropdown">
<button class="dropbtn">{{ link.title }}
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<div class="mm-row">
<div class="mm-column">
<div class="mm-subcategory">
<i class="fas fa-arrow-left" onclick="closeDropDown()"></i>
<h3>{{ link.title | link_to: link.url }}</h3>
</div>
{% for child_link in linklists[child_list_handle].links %} {{ child_link.title | link_to: child_link.url }} {% endfor %}
</div>
<div class="dropdown-feature">
{% assign collection= collections.winter-wear %}
<img src="{{ collection.image | img_url: '908x330' }}">
</div>
</div>
</div>
<!-- /dropdown-content -->
</div>
解决方案
querySelectorAll 函数返回一个节点数组。请改用 querySelector。
function closeDropDown() {
const temp = document.querySelector(".mobile-nav .dropdown-content");
temp.classList.remove("active");
}
function myFunction() {
var element = document.querySelector("#myDIV");
element.classList.remove("bgStyle");
}
.bgStyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
<p>Click the "Try it" button to remove the "mystyle" class from the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV" class="bgStyle">
This is a DIV element.
</div>
推荐阅读
- javascript - 解构 JavaScript 返回错误
- c++ - 循环不在函数 C++ 中执行
- php - 在 public_html 之外包含文件
- java - grpc-java 的 TCP 传输
- vue.js - 为什么服务器找不到我的 build.js 文件?
- python - 如何提高 csv 函数 python 的运行时间
- visual-studio-code - VSCode 和 WSL 的权限问题(代码:找不到命令)
- typescript - 如何为路由组成这个嵌套接口
- mysql - 我们如何在 MongoDB 和 MySQL 中使用 solr?
- sockets - Nginx 和 uWSGI:502 Bad Gateway 问题的正确权限设置