javascript - 在 ASP.NET MVC 视图中切换 aria-pressed=true/false 查看引发错误
问题描述
当我点击一个按钮时,我必须切换.active类的 bootstrap 和aria-pressed=true/false来处理 asp.net MVC 视图中的可访问性。对于单击的按钮,我已将 .active 和 aria-pressed 设置为 true,将其余按钮设置为 false。我已经完成了以下代码来更改 CSS 类名和属性。CSS 类 .active 工作正常,但我收到错误消息
“未捕获的 TypeError:无法读取 HTMLButtonElement 处未定义的属性‘setAttribute’。”
你能帮我解决这个错误吗?
@{
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>
解决方案
哇,所有实现这一目标的代码!你已经在使用 JQuery,所以你为什么不尝试这样的事情(删除你所有的 javascript 代码并用这个替换它):
<script type="text/javascript">
$(document).ready(function () {
$("#containerDiv .btn").click(function () {
$("#containerDiv .btn").attr("aria-pressed", false)
$("#containerDiv .btn").removeClass("active")
$(this).attr("aria-pressed", true)
$(this).addClass("active")
});
});
</script>
推荐阅读
- javascript - 在 Javascript 中使用按钮显示和隐藏元素
- android - Firebase 存储错误:参数无效:“_File”实例
- java - 处理从文件读取的值时的最佳实践
- r - 如何使用 dplyr lag() 平滑变量中的微小变化
- c++ - C6001 关于使用未初始化值的地址。为什么?
- java - Android Java Firebase runTransaction 在类不完全相同时删除值
- java - “对象='用户'的验证失败。错误计数:1”而不是“电子邮件不能为空”
- java - 对来自 Firestore 的旧数据的新数据进行分页
- python - 在 sklearn 管道中转换估计器的结果
- c# - 动态生成表单的 Dotnet 核心 MVC 服务器端验证