首页 > 解决方案 > 更改按钮的背景颜色(开/关)

问题描述

我已经审查了这个问题,但我没有使用角度。

到目前为止,这是我的代码:

<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;
}

有什么建议吗?

标签: javascripthtmlcss

解决方案


很简单,你不需要#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>

推荐阅读