gpt4 book ai didi

javascript - 如何 'Add active class to the current button'

转载 作者:行者123 更新时间:2023-12-02 23:04:28 25 4
gpt4 key购买 nike

我在 Shopify 网站的页面上有以下代码,但按钮在事件时不会改变颜色。当我在 bootply 上尝试时似乎工作正常,但在 shopify 上却无法工作。我在控制台中看到的错误是 Uncaught TypeError: "Cannot read property 'getElementsByClassName' of null""

<script>
filterSelection("all")
function filterSelection(c) {
var x, i;
x = document.getElementsByClassName("column");
if (c == "all") c = "";
for (i = 0; i < x.length; i++) {
w3RemoveClass(x[i], "show");
if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
}
}

function w3AddClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
if (arr1.indexOf(arr2[i]) == -1) { element.className += " " + arr2[i]; }
}
}

function w3RemoveClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
while (arr1.indexOf(arr2[i]) > -1) {
arr1.splice(arr1.indexOf(arr2[i]), 1);
}
}
element.className = arr1.join(" ");
}


// Add active class to the current button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function () {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
</script>

最佳答案

最好等待 DOM 完全加载所有元素 - 之后进行操作

document.addEventListener("DOMContentLoaded", function() {  
// Place class assigning code here
// Add active class to the current button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function () {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
// Place filter selection also inside DOM Load
filterSelection("all");
});

关于javascript - 如何 'Add active class to the current button',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57651080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com