我正在尝试在类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);
});
有没有办法让它适用于所有元素而不重复代码?
答案 0 :(得分:0)
原来我只需使用querySelectorAll
代替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);
});
}