javascript - 更改按钮的背景颜色(开/关)
问题描述
我已经审查了这个问题,但我没有使用角度。
到目前为止,这是我的代码:
<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>Bx</button>
<button id='By' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>By</button>
<button id='Bz' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>Bz</button>
像我这样的JS:
function toggleClickedBuz( bizStr , id ) {
if(clickedBusinesses.includes(bizStr)){
// removing duplicate element from that array, dependant on button pressed
clickedBusinesses = clickedBusinesses.filter( cb => cb !== bizStr );
document.getElementById( id ).style.backgroundColor='white';
}else{
// else push it to the array
clickedBusinesses.push(bizStr)
document.getElementById( id ).style.backgroundColor='red';
}
console.log(clickedBusinesses)
}
但我收到此错误:
未捕获的类型错误:无法读取 null 的属性“样式”
尽管在我的 CSS 中有这个:
.canvas .button-box button {
border-radius: 2px;
width: 10vw;
margin-top: 0.5vh;
background-color: whitesmoke;
}
有什么建议吗?
解决方案
很简单,你不需要#
in toggleClickedBuz("Bx", "#Bx")
。不放。id
_ #
该函数getElementById()
已经引用了 id。所以你不需要指定使用#
.
你的 HTML 应该像
<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>Bx</button>
<button id='By' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>By</button>
<button id='Bz' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>Bz</button>
推荐阅读
- java - 如何在 UTC 区域中获取当前日期作为 java 8 中的长值
- laravel - 如何覆盖 laravel DatabaseManager 方法
- html - 具有响应的宽度和高度的图像的说明
- c++ - 没有可行的重载+=,为什么?
- apache-kafka - WSO2流处理器,json错误“包含缺少的属性”与kafka
- angular - 仅在分隔符上拆分并在该分隔符上显式拆分
- state-machine - 两个十进制数相加的图灵机
- android - 当初始化改造我得到错误:KotlinNullPointerException
- bash - Bash函数是否可以将值输出到文件描述符,然后仅将其分配给变量?
- c# - <>0 和 >0 之间哪个布尔求值最快?