【发布时间】:2019-08-06 16:18:05
【问题描述】:
当我点击一个按钮时,我必须切换 .active 类的引导程序和 aria-pressed=true/false 来处理 asp.net MVC 视图中的可访问性。对于单击的按钮,我已将 .active 和 aria-pressed 设置为 true,将其余按钮设置为 false。我已经完成了以下代码来更改 CSS 类名和属性。 CSS 类 .active 工作正常,但我收到一个错误,因为
“未捕获的类型错误:无法读取未定义的属性'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>
【问题讨论】:
标签: javascript jquery asp.net-mvc