首页 > 解决方案 > 从 nodeList javascript 获取数据集值

问题描述

我有一个 div 的 nodeList,每个 div 都有一个带有 src、id 和数据集的 img。当使用 forEach 循环循环 nodeList 时,我存储了该 div 的第一个元素(因此是 img),因此我可以访问它的 id、src 和数据集。我成功获得了 id 和 src 但没有获得数据集;它总是返回一个空的 DOMStringMap {} 。

我怎样才能得到这个信息?

每个 div 都有一个 img like ->


        function getCards(){
            let totalCards = document.querySelectorAll(".card")

            totalCards.forEach(el => {

                el.addEventListener("click", function(){
                    let thisCard = el.children[0]
                    let thisCardID = thisCard.id
                    let thisCardDataSet = thisCard.dataset
                    let thisCardSRC = thisCard.src

                    console.log(thisCard)
                    console.log(thisCardID)
                    console.log(thisCardDataSet)
                    console.log(thisCardSRC)

                })

            })
            //console.log(flippedCard)
        }
´´´

标签: javascriptnodelist

解决方案


如果数据集是img标签的属性,如下所示:

<img src=".." alt=".." dataset="..." />

然后你需要先获取属性对象

let thisCardDataSet = thisCard.attributes.dataset

推荐阅读