javascript - 将类添加到具有匹配数据属性值的元素

标签 javascript html css loops

我想使用 vanilla JS 向共享相同数据属性值的元素添加一个类。该类在 mouseenter 上添加。

我当前的设置仅将鼠标悬停时的类应用于第一个元素,而忽略其余元素。

let section = document.querySelector('.section');
let links = document.querySelectorAll('.links a');
let triggerVal;
let linkedVal;

links.forEach(function(link, index) {
  link.addEventListener('mouseenter', function() {
    triggerVal = this.dataset.triggerValue;
    linkedVal = section.dataset.linkedValue;

    if (linkedVal === triggerVal) {
      section.classList.add('is-active');
    } else {
      section.classList.remove('is-active');
    }
  });
});
<ul class="links">
  <li>
    <a data-trigger-value="red" href="#">Red</a>
  </li>
  <li>
    <a data-trigger-value="yellow" href="#">Yellow</a>
  </li>
  <li>
    <a data-trigger-value="blue" href="#">Blue</a>
  </li>
</ul>

<div class="wrapper">
  <div class="section" data-linked-value="red">
    <h2>Red</h2>
  </div>
  <div class="section" data-linked-value="yellow">
    <h2>Yellow</h2>
  </div>
  <div class="section" data-linked-value="blue">
    <h2>Blue</h2>
  </div>
</div>

这是一个代码笔:https://codepen.io/abbasarezoo/pen/7378e190ed6ad117faca968b634520b0

我觉得这与 .section 元素有关,但我尝试了一些方法,但似乎没有任何东西能满足我的需要。

关于我需要做什么才能使其余元素正常工作,有什么建议吗?

最佳答案

你需要改变两件事:

首先,获取所有部分:

const section = document.querySelectorAll('.section');

然后,在您的处理程序中,您需要遍历 querySelectorAll() 返回的 NodeList:

    for (const section of sections) {
        linkedVal = section.dataset.linkedValue;

        if (linkedVal === triggerVal) {
            section.classList.add('is-active');
        } else {
            section.classList.remove('is-active');
        }   
    }

这是你的新 JS:

const sections = document.querySelectorAll('.section');
const links = document.querySelectorAll('.links a');
let triggerVal;
let linkedVal;

links.forEach(function(link, index){
  link.addEventListener('mouseenter', (e) => {
        triggerVal = e.target.dataset.triggerValue;
        for (const section of sections) {
            linkedVal = section.dataset.linkedValue;

            if (linkedVal === triggerVal) {
                section.classList.add('is-active');
            } else {
                section.classList.remove('is-active');
            }   
        }
    });
});

关于javascript - 将类添加到具有匹配数据属性值的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52081307/

相关文章:

javascript - 输入类型之间的 DOM/jQuery 事件传播差异

html - 绝对定位图像和滚动条

html - 为什么我的 HTML h1 元素跨越两行,但它有足够的空间可以使用一行?

javascript - 如何在ckeditor中自定义工具栏?

html - 将 TD 对齐到 TABLE 的右侧

javascript - 将文件作为字符串上传到 JavaScript 变量

html - iPhone 浏览器不显示 CSS Sprite

jquery - 如何使每篇文章的盒子高度相同,这样就没有空白

JavaScript:在其他函数中评估函数

javascript - 如何将变量转为选项?