Snackbar 仅适用于某些 class 的一个元素

Snackbar works only on one element of certain class

我正在尝试在所有带有 class add-culture-button 的按钮上为 snackbar 添加事件侦听器,但它仅适用于第一个元素。对于其他元素,snackbar 根本不显示(并且控制台中没有错误)。

var snackbarContainer = document.querySelector("#notification");
var showSnackbarButton = document.querySelector(".add-culture-button");
var plantingLabel = document.querySelector("#planting-label");
var handler = function(event) {
    var culturesCount = parseInt(plantingLabel.attributes["data-badge"].value);
    plantingLabel.setAttribute("data-badge", culturesCount - 1);
}

showSnackbarButton.addEventListener("click", function() {
    var culturesCount = parseInt(plantingLabel.attributes["data-badge"].value);
    plantingLabel.setAttribute("data-badge", culturesCount + 1);
    var data = {
        message: "Kultura je dodata u listu za setvu.",
        timeout: 2000,
        actionHandler: handler,
        actionText: 'Opozovi'
    };
    snackbarContainer.MaterialSnackbar.showSnackbar(data);
});

有没有办法让它在不重复代码的情况下适用于所有元素?

原来我只需要使用 querySelectorAll instead of querySelector...

var snackbarContainer = document.querySelector("#notification");
var showSnackbarButton = document.querySelectorAll(".add-culture-button");
var plantingLabel = document.querySelector("#planting-label");
var handler = function(event) {
    var culturesCount = parseInt(plantingLabel.attributes["data-badge"].value);
    plantingLabel.setAttribute("data-badge", culturesCount - 1);
}

for (var i = 0; i < showSnackbarButton.length; i++) {
    showSnackbarButton[i].addEventListener("click", function() {
        var culturesCount = parseInt(plantingLabel.attributes["data-badge"].value);
        plantingLabel.setAttribute("data-badge", culturesCount + 1);
        var data = {
            message: "Kultura je dodata u listu za setvu.",
            timeout: 2000,
            actionHandler: handler,
            actionText: 'Opozovi'
        };
        snackbarContainer.MaterialSnackbar.showSnackbar(data);
    });
}