Мне нужно переключить .active класс начальной загрузки и aria-press = true / false для обработки доступности в виде asp.net MVC, пока я нажимаю на кнопку. Я установил для .active и aria -ressed значение true для нажатой кнопки и false для остальных кнопок. Я сделал следующий код, чтобы изменить CSS className и атрибут. Класс CSS .active работает, но я получаю ошибку как
"Uncaught TypeError: Невозможно прочитать свойство 'setAttribute' из неопределенного
в HTMLButtonElement. "
Не могли бы вы помочь мне устранить ошибку?
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>MyTest</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
<script type="text/javascript">
$(document).ready(function () {
var btnContainer = document.getElementById("containerDiv");
// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("btn");
// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function () {
var current = document.getElementsByClassName("active");
// If there's no active class
if (current.length > 0) {
current[0].className = current[0].className.replace(" active", "");
current[0].setAttribute("aria-pressed", "false");
}
// Add the active class to the current/clicked button
this.className += " active";
this.setAttribute("aria-pressed", "true");
});
}
});
</script>
</head>
<body>
<div id="containerDiv">
<button class="btn btn-primary" type="button" aria-pressed="false">
Product 1
</button>
<button class="btn btn-primary" type="button" aria-pressed="false">
Product 2
</button>
<button class="btn btn-primary" type="button" aria-pressed="false">
Product 3
</button>
<button class="btn btn-primary" type="button" aria-pressed="false">
Product 4
</button>
<button class="btn btn-primary" type="button" aria-pressed="false">
Product 5
</button>
</div>
</body>
</html>