javascript - 如何将变量与 nth-child 选择器一起使用?
问题描述
当我单击右侧的箭头时,我想从一组 20 个选项卡中隐藏第一个(通过删除类“w--tab-active”并显示第二个(通过添加类“w-- tab-active”)。当我再次单击时,我想隐藏第二个选项卡并显示第三个选项卡。显然我不能在 nth-child 选择器中使用变量,对吧?那我还能如何实现这个目标呢?
这就是我的代码的样子:
var tabToHide = document.querySelector('.w-tab-content div:nth-child(1)');
tabToHide.classList.remove("w--tab-active");
var tabToShow = document.querySelector('.w-tab-content div:nth-child(2)');
tabToShow.classList.add("w--tab-active");
查看此网址下的代码:https ://der-gottwald-de.webflow.io/karussell-test
解决方案
您可以获取其类所在的元素列表。w-tab-content
. 然后你只需要从数组中取出第一个或第二个。这里使用 [1] 而不是 nth-child(1)。
var tabToHide = document.querySelector('.w-tab-content')[0]; //this returns an array with the list of .w-tab-content, [0] will take the first one.
tabToHide.classList.remove("w--tab-active");
var tabToShow = document.querySelector('.w-tab-content' )[1];//[1] will take the second one.
tabToShow.classList.add("w--tab-active");
你能试试这个,让我们知道它是如何工作的吗?
推荐阅读
- semantic-mediawiki - 我可以在语义媒体维基中使用属性值作为查询吗?
- python - Python Pandas 到 PySpark:如何在 PySpark 中标记化、删除权宜之计和做三元组
- database - 如何在数据库中保存应用程序密码?
- sql-server - 在 NOT NULL 处重新启动的 NULL 累积计数
- python - 使用 rabbitmq 集成 Nodejs 和 Python
- c++ - 在编译时验证对象是否创建为 shared_ptr
- c# - 我想避免用户使用 mvc 5 同时登录多个地方
- traefik - Kubernetes 上的 Traefik UI 中缺少“最近的 HTTP 错误”
- python - 从 keras 生成器获取真实标签
- vue.js - vue2-autocomplete-js 不像文档中提到的那样工作