简体   繁体   English

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

[英]Add a class to element with matching data attribute value

I want to add a class to an element that shares the same data attribute value using vanilla JS. 我想使用香草JS向共享相同数据属性值的元素添加一个类。 The class is added on mouseenter . 该类添加在mouseenter

My current setup only applies the class on hover to the first element and ignores the rest. 我当前的设置仅将鼠标悬停时的类应用于第一个元素,而忽略其余元素。

 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> 

Here's a Codepen: https://codepen.io/abbasarezoo/pen/7378e190ed6ad117faca968b634520b0 这是一个Codepen: https ://codepen.io/abbasarezoo/pen/7378e190ed6ad117faca968b634520b0

I've got a feeling it's to do with the .section element but I've tried a few things and nothing seems to give me what I need. 我觉得这与.section元素有关,但是我尝试了几件事,但似乎没有任何东西.section我的需求。

Any suggestions as to what I need to do to get the rest of the elements working? 关于我需要做什么才能使其余元素正常工作的任何建议?

You need to change two things: 您需要更改两件事:

First, get all sections: 首先,获取所有部分:

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

Then, inside your handler, you need to iterate over the NodeList returned by querySelectorAll() : 然后,在处理程序内部,您需要遍历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');
        }   
    }

This is your new JS: 这是您的新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');
            }   
        }
    });
});

You need to use document.querySelectorAll for sections and then forEach . 您需要将document.querySelectorAll用于sections ,然后用于forEach And use toggle instead of add/remove for this case. 并在这种情况下使用toggle而不是add/remove https://developer.mozilla.org/en-US/docs/Web/API/Element/classList https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

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

links.forEach(function(link, index) {
  link.addEventListener('mouseenter', function() {
    triggerVal = this.dataset.triggerValue;
    sections.forEach(
        section => section.classList.toggle(
            'is-active',
            section.dataset.linkedValue === triggerValue
        )
    );
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从元素中获取数据属性并添加 class - Get data attribute from element and add class 使用动态添加的数据属性将类添加到元素 - Add class to element with dynamically added data attribute 使用vanilla javascript添加匹配类名的增量数据属性 - Add incremental data attribute matching class names with vanilla javascript 如何在元素 html 内部添加元素数据属性值 - How to add element data attribute value inside of the element html 获取数据属性的JSON值,并在特定DOM元素中搜索匹配的Json键-&gt;数据属性 - Acquiring the JSON value of a data attribute, and search for matching Json key -> data attribute in a specific DOM element 将Data属性添加到元素并从string中动态添加值 - Add Data attribute to element and dynamically add value from string 通过使用html自定义属性值将类名称添加到html元素 - Add class name to a html element by using html custom attribute value 根据 ID 和特定属性值向元素添加 CSS 类 - Add CSS class to element based on the ID and a specific attribute value 我可以选择一个<element>通过模式匹配 data-* 属性名称(不是属性值)? - Can I select an <element> by pattern matching a data-* attribute name (not the attribute value)? 使用 label 按数据属性获取元素并添加禁用的 class - Get element by data attribute using label and add disabled class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM