[英]Changing the background colour of a button (On/Off)
I have reviewed This Question but I am not using angular.我已经查看了这个问题,但我没有使用 angular。
Here is my code so far:到目前为止,这是我的代码:
<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>
With my JS like this:像我这样的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)
}
But I am getting this error:但我收到此错误:
Uncaught TypeError: Cannot read property 'style' of null
未捕获的类型错误:无法读取 null 的属性“样式”
Despite having this in my CSS:尽管在我的 CSS 中有这个:
.canvas .button-box button {
border-radius: 2px;
width: 10vw;
margin-top: 0.5vh;
background-color: whitesmoke;
}
Any advice?有什么建议吗?
Simple, You don't need #
in toggleClickedBuz("Bx", "#Bx")
.很简单,您不需要
#
in toggleClickedBuz("Bx", "#Bx")
。 Put id
without #
.把
id
不带#
。 The function getElementById()
already refers the id. function
getElementById()
已经引用了 id。 So you don't need to specify using #
.所以你不需要指定使用
#
。
Your HTML should be like你的 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>
Given following HTML给出以下 HTML
<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>Bx</button>
You are passing #Bx
as id argument to your toggle function.您将
#Bx
作为 id 参数传递给您的切换 function。 This results in the js call:这导致 js 调用:
document.getElementById("#Bx");
But the getElementById
function does not require the #
prefix.但是
getElementById
function 不需要#
前缀。 Try to change your HTML to尝试将您的 HTML 更改为
<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>Bx</button>
to hotfix your current problem修复您当前的问题
You do not need #
in your button.您的按钮中不需要
#
。 This much is enough:这么多就够了:
<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>
#
is a CSS selector whuch selects your HTML id
elements. #
是一个 CSS 选择器,用于选择您的 HTML id
元素。 You can reference them in your CSS in this manner:您可以通过以下方式在 CSS 中引用它们:
#Bx {
color: #AAAAAA;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.