簡體   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