点击按钮时添加和删除边框JS
你好,我正在努力使用 JS 来使我的 HTML 页面上的按钮在单击时为按钮添加边框,并在再次单击时删除边框。它适用于前两次点击,但此后不再执行任何操作。请原谅我的 js 我非常缺乏经验。
JavaScript:
<script>
var flag = true;
var buttons = document.getElementsByClassName("btn");
function buttonFunction() {
if (flag) {
for (var i = 0; i < buttons.length; i++) {
document.getElementsByClassName("btn")[i].addEventListener("click", function() {
this.classList.add("buttonSelect");
flag = false
return
});
}
} else {
if (flag == false) {
for (var i = 0; i < buttons.length; i++) {
document.getElementsByClassName("btn")[i].addEventListener("click", function() {
this.classList.add("buttonUnselect");
flag = true
return
});
}
}
}
}
</script>
hello I am struggling to use JS in order to make the buttons on my HTML page add a border to the button when it is clicked and to remove the border when it is clicked again. it works for the first 2 clicks but then no longer does anything after that. please excuse my js im extremely inexperienced.
JavaScript:
<script>
var flag = true;
var buttons = document.getElementsByClassName("btn");
function buttonFunction() {
if (flag) {
for (var i = 0; i < buttons.length; i++) {
document.getElementsByClassName("btn")[i].addEventListener("click", function() {
this.classList.add("buttonSelect");
flag = false
return
});
}
} else {
if (flag == false) {
for (var i = 0; i < buttons.length; i++) {
document.getElementsByClassName("btn")[i].addEventListener("click", function() {
this.classList.add("buttonUnselect");
flag = true
return
});
}
}
}
}
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
真正的问题是您添加了这两个类并且从未删除它们。摆脱
if else
语句,只需单击即可切换类。也不需要将循环包装在函数中。只需让 javascript 在运行时执行事件侦听器即可。另外,请使用您创建的
buttons
var,而不是尝试再次查询 DOM 来查找相同的元素。The real issue is you're adding both classes and never removing them. Get rid of the
if else
statement and just toggle the class on click. Don't need to wrap the loop in a function either. Just let the javascript execute the event listeners at runtime.Also, make use of the
buttons
var you created instead of trying to query the DOM again for the same elements.