首页 > 解决方案 > 如何将变量与 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

标签: javascriptcss-selectors

解决方案


您可以获取其类所在的元素列表。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");

你能试试这个,让我们知道它是如何工作的吗?


推荐阅读