Javascript 数据属性返回为未定义,但不应返回';T我哪里出错了?

Javascript 数据属性返回为未定义,但不应返回';T我哪里出错了?,javascript,html,css,Javascript,Html,Css,因此,我目前正在做一项作业,我们必须使用下拉列表中的项目制作购物车。此列表是使用json文件中的项目填充的。为了使它们具有唯一性,我使用javascript为每个项目提供了一些数据属性。这一切似乎都很好,直到我真的尝试添加到我的购物车 目前,我试图使用console日志将该项记录在控制台中,但它始终以未定义的状态返回。我哪里出错了?这是代码 "use strict"; const btn = document.getElementById('add'); const choi

因此,我目前正在做一项作业,我们必须使用下拉列表中的项目制作购物车。此列表是使用json文件中的项目填充的。为了使它们具有唯一性,我使用javascript为每个项目提供了一些数据属性。这一切似乎都很好,直到我真的尝试添加到我的购物车

目前,我试图使用console日志将该项记录在控制台中,但它始终以未定义的状态返回。我哪里出错了?这是代码

"use strict";
const btn = document.getElementById('add');
const choiceList= document.getElementById('vegetables');
getVeggies();

async function getVeggies() {
    const response = await fetch("veggies.json")
        if (response.ok) {
            const veggies = await response.json();
            transferVeggies(veggies);
        } else {
            console.log("oops something went wrong!");
        }
};

function transferVeggies(veggies) {
    
    for (const veggie of veggies) {
        addVeggiesToList(veggie);
    }
};

function addVeggiesToList(veggie) {
    let veggieChoice= document.createElement("option");
    veggieChoice.dataset.name = veggie.name;
    veggieChoice.dataset.price = veggie.price;
    veggieChoice.dataset.unit = veggie.unit;
    veggieChoice.innerText = veggie.name + '(' +`${veggie.price}`+"/"+`${veggie.unit}`+')';
    choiceList.appendChild(veggieChoice);

}

btn.onclick = function() {
    addVeggieToBasket(choiceList);
}

function addVeggieToBasket(choiceList) {
   console.log(choiceList.value); //THIS WORKS AND RETURNS THE INNERTEXT DECLARED IN ADDVEGGIESTOLIST
   console.log(choiceList.dataset.name); //THIS JUST RETURNS UNDEFINED
   console.log(choiceList.value.dataset.name); //SAME PROBLEM AS ABOVE, IT RETURNS UNDEFINED

}
我还应该说,声明数据属性没有问题,因为我可以看到它们在控制台中出现。我认为问题在于,数据属性是在一个函数中声明的,因此它们只能在同一个函数中调用,但这对我来说毫无意义


有人知道我该如何做吗?

使用
options
selectedIndex
获取option元素

function addvegietobasket(选择列表){
console.log(choiceList.value);
log(choiceList.options[choiceList.selectedIndex].dataset.name);
}

数据属性位于
choiceList
元素中的子元素上,以获取所有元素的属性循环
choiceList.children
并获取其数据集属性。