繁体   English   中英

在等于变量的类中查找数据属性

[英]Find a data-attribute within a class that is equal to a variable

请不要jquery我试图删除列表中具有与foo相同的数据ID的元素

let foo = document.querySelector('.foo');
let list = document.querySelector('.listing-filter');
let fooId = foo.dataset.id;
let listId = list.dataset.id;

let listingFilter = () => {
    if ( typeof fooId !== 'undefined' && typeof listId !== 'undefined'){
        //This is what I cant seem to figure out
        let deleteMe = document.querySelector('.listing-filter[data-id = fooId]')

        //This should only be the data-id in list that changes not in el1
        deleteMe.setAttribute('data-id', 'hidden')
     }
}

然后在CSS中,我可以选择它[data-id =“ hidden”]并隐藏该元素。

我似乎无法弄清楚如何在列表中选择与foo具有相同data-id的list元素,然后对其进行操作。

document.querySelector('.listing-filter[data-id="fooId"]')

您可以尝试更新查询选择器字符串吗?

你快到了:

let deleteMe = document.querySelector('.listing-filter [data-id="' + fooId + '"]');

而且你不需要.foo

let list = document.querySelector('.listing-filter');
let listId = list.dataset.id;

let listingFilter = () => {
    if (typeof listId !== 'undefined'){
      let deleteMe = document.querySelector('.listing-filter [data-id="' + listId + '"]');
      deleteMe.setAttribute('data-id', 'hidden')
    }
}

您直接输入fooId ,因此它将查找带有data-id="fooId"而不是您定义的fooId值。 尝试将变量添加到字符串中:

let deleteMe = document.querySelector(`.listing-filter[data-id=${fooId}]`)

暂无
暂无

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

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