简体   繁体   English

从元素中获取数据属性并添加 class

[英]Get data attribute from element and add class

This jquery code works and it is in use, but somehow my items filter not working with it correctly.此 jquery 代码有效并且正在使用中,但不知何故我的项目过滤器无法正确使用它。 But somehow my vanilla js working with that filter I use.但不知何故,我的香草 js 与我使用的那个过滤器一起工作。

So my question is:所以我的问题是:

How I can change this jquery code to vanilla js?如何将此 jquery 代码更改为 vanilla js?

$(".cat-name .cat-link").click(function () {

    let catID = $(this).data("id"),
        $allItem = $('.category')

    let $currentItem = $('.cat[data-category=' + catID + ']');
   
    $('.cat[data-category=' + catID + ']').addClass('active');
        $allItem.not($currentItem).removeClass('active');
    
    $('.all-items').removeClass('active'); // Remove active class from "All Items" tab
   
   });

Thanks if you have time to help me!感谢您有时间帮助我!

Here is a quick answer:这是一个快速的答案:

  • use document.querySelector() and document.querySelectorAll() to select element(s)使用document.querySelector()document.querySelectorAll()到 select 元素
  • use targetElement.addEventListener('click', function() {... }) to add click event使用targetElement.addEventListener('click', function() {... })添加点击事件
  • use targetElement.className to add/remove classes使用targetElement.className添加/删除类
  • use targetElement.getAttribute('data-...') to manage data attributes使用targetElement.getAttribute('data-...')管理数据属性

Remember to visit Vanilla JS website for more examples记得访问Vanilla JS 网站以获取更多示例

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM