类别列表可在多个元素上切换 [英] Classlist toggle on multiple elements

查看:41
本文介绍了类别列表可在多个元素上切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有正常运行的代码,但是我敢肯定有一种写得更干净的方法.

I have functioning code, but I am sure there is a way to write it cleaner.

我的代码与我认为的最佳实践相去甚远.不要重复自己的原则.

My code is far from best practice I assume. Don't repeat yourself principle.

我尝试寻找此问题,但找不到答案.

I have tried looking for this problem but can not find an answer.

这是预期结果和我当前的代码: https://jsfiddle.net/9ednsp6x/

Here are the expected result and my current code: https://jsfiddle.net/9ednsp6x/

document.getElementById("BtnMoreTotalt").onclick = function() {MoreBtnTotalt()};
function MoreBtnTotalt() {
    document.querySelector(".more-wrapper-totalt").classList.toggle("show");
}

我也想知道,是否有办法让我不必在每个元素上使用特定的id和classname?我只能使用类"more-wrapper"并跳过ID吗?

I also wonder, if there is a way so I do not have to use specific id and classnames on every element? Could I only use class "more-wrapper" and skip the IDs?

推荐答案

document.querySelectorAll(".more-button").forEach(element => {
  element.onclick = (e) => {
    const elm = document.getElementsByClassName(e.target.getAttribute("anchor"));
    elm[0].classList.toggle("show");
  };
});

.more-wrapper {
  visibility:hidden;
}
.more-wrapper.show {visibility:visible};

<div class="more-wrapper more-wrapper-totalt">
  <div>test1</div>
</div>
<a href="#" onClick="return false;">
  <div anchor="more-wrapper-totalt" class="more-button">Mer info</div>
</a>

<div class="more-wrapper more-wrapper-kvant">
  <div>test2</div>
</div>
<a href="#" onClick="return false;">
  <div anchor="more-wrapper-kvant" class="more-button">Mer info</div>
</a>

<div class="more-wrapper more-wrapper-invb">
  <div>test3</div>
</div>
<a href="#" onClick="return false;">
  <div anchor="more-wrapper-invb" class="more-button">Mer info</div>
</a>

<div class="more-wrapper more-wrapper-barn">
  <div>test4</div>
</div>
<a href="#" onClick="return false;">
  <div anchor="more-wrapper-barn" class="more-button">Mer info</div>
</a>

使用此attr click事件后,可以添加带有属性的className按钮.就像克隆,但我认为您需要在另一个地方上这个课.

You can add the className button with attribute after use this attr click event. It's like clone but i think you need this class another place.

这篇关于类别列表可在多个元素上切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆