包含 getAttribute 的函数中没有 returns

No returns from a function which contains getAttribute

我正在尝试显示按钮的值,但是当我按下按钮时,控制台中没有显示任何内容。

我遗漏了一些东西,我想不通。

 const allButtons = document.querySelector("[data-buttons]");

    Array.from(allButtons).forEach(button => {
        button.addEventListener("click", () => {
            let userPick = button.getAttribute("[data-pick]");
            console.log(userPick);
        });
    });

谢谢! :)

您需要使用 dataset 对象才能读取 data- 相关属性,像这样

const allButtons = document.querySelectorAll("[data-buttons]");

Array.from(allButtons).forEach(button => {
    button.addEventListener("click", () => {
        let userPick = button.dataset.pick;
        console.log(userPick);
    });
});

请看下面的注释代码:

// USE "querySelectorAll" INSTEAD OF "querySelector" TO ACTUALLY GET AN ARRAY-LIKE (NodeList) RESULT.
const allButtons = document.querySelectorAll("[data-buttons]");

// YOU CAN DIRECTLY USE "forEach" ON A NodeList INSTANCE.
allButtons.forEach(button => {
    button.addEventListener("click", ({target}) => {
        // "getAttribute" NEEDS ATTRIBUTE NAME AS INPUT WITHOUT "[]".
        // YOU CAN USE "e.target" INSTEAD OF "button" HERE.
        const userPick = target.getAttribute("data-pick");
        console.log(userPick);
    });
});
<button data-buttons data-pick="A">Button A</button>
<button data-buttons data-pick="B">Button B</button>
<button data-buttons data-pick="C">Button C</button>
<button data-buttons data-pick="D">Button D</button>
<button data-buttons data-pick="E">Button E</button>

如果您有多个按钮,则需要使用 querySelectorAll

 const allButtons = document.querySelectorAll("[data-buttons]");

    Array.from(allButtons).forEach(button => {
        button.addEventListener("click", () => {
            let userPick = button.getAttribute("data-pick");
            console.log(userPick);
        });
    });
<button data-buttons="1" data-pick="1"> 1</button>
<button data-buttons="2" data-pick="2"> 2</button>
<button data-buttons="3" data-pick="3"> 3</button>

可以直接循环querySelectorAll

返回的Nodelist

document.querySelectorAll("[data-buttons]").forEach(button => {
  button.addEventListener("click", () => {
    let userPick = button.getAttribute("data-pick");
    console.log(userPick);
  });
});
<button data-buttons="1" data-pick="1"> 1</button>
<button data-buttons="2" data-pick="2"> 2</button>
<button data-buttons="3" data-pick="3"> 3</button>