如何定位特定的div,然后切换类?

时间:2019-05-07 13:34:08

标签: javascript jquery html css

例如,我有这个菜单:

function toggleHiddenContent(tabClass) {
    let t = document.querySelectorAll(tabClass);
    for(var i = 0; i<t.length; i++) {
        t[i].classList.toggle="visible-class";
    }
}
.hidden-content {
    display: none;
}
.visible-class {
    display: block
}
<div>
    <a class="main-holder" onClick="toggleHiddenContent('.main-holder')">Main one</a>
    <div class="hidden-content">Hidden content One</div>

    <a class="main-holder" onClick="toggleHiddenContent('.main-holder')">Main two</a>
    <div class="hidden-content">Hidden content two</div>
</div>

但是,它会切换所有类。我确实知道问题出在哪里,但是我该如何匹配仅被单击的一个而不与未激活(单击)的那个匹配?

我在香草js中需要它

谢谢大家

3 个答案:

答案 0 :(得分:3)

classList.toggle是一个函数,而不是可分配的属性

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

尝试

function toggleHiddenContent(tabClass) {
  let t = document.querySelectorAll(tabClass);
  for (var i = 0; i < t.length; i++) {
    t[i].classList.toggle("visible-class");
  }
}

根据您的示例,我建议您进行一些小的更改,这些更改将提高可读性,例如设置父项<div>(使查找父项变得容易),以及从HTML删除onClick。看看

fiddle

从下面的答案中,我不知道nextElementSibling,它不需要您像我建议的那样更改HTML

答案 1 :(得分:1)

您可以尝试以下方法:

function toggleHiddenContent(e) {
    if (e.target.nextElementSibling.classList.contains("visible-class") ) {
        e.target.nextElementSibling.className = "hidden-content";
      
    } else {
        e.target.nextElementSibling.className = "visible-class";   
    }
}
.hidden-content {
    display: none;
}
.visible-class {
    display: block
}
<div>
    <a class="main-holder" onClick="toggleHiddenContent(event)">Main one</a>
    <div class="hidden-content">Hidden content One</div>

    <a class="main-holder" onClick="toggleHiddenContent(event)">Main two</a>
    <div class="hidden-content">Hidden content two</div>
</div>

答案 2 :(得分:1)

您可以尝试执行以下操作(并防止使用干扰性的javascript):

//Get the element(s) you want to interact with and store these in an array:
let myElements = document.getElementsByClassName("main-holder");
//Loop through the array to add an event listener to every interactable element:
for (let i = 0; i < 10; i++) {
  if (myElements[i]) {
    myElements[i].addEventListener("click", function() {
      //Your function:
      toggleHiddenContent("visible-class", i);
    });
  }
}

function toggleHiddenContent(tabClass, target) {
  //Get the element(s) you want to manipulate (or adjust) and store these in an array:
  let targetElements = document.getElementsByClassName("hidden-content");
  //Use the index you got from clicking on the previous element to determine which targeted element to manipulate (or adjust):
  targetElements[target].classList.toggle(tabClass);
}
.hidden-content {
  display: none;
}

.visible-class {
  display: block;
}
<div>
  <a class="main-holder">Main one</a>
  <div class="hidden-content">Hidden content One</div>

  <a class="main-holder">Main two</a>
  <div class="hidden-content">Hidden content two</div>
</div>

JSFiddle

如果您需要更多信息,请在评论中告诉我。