![](/img/trans.png)
[英]React/Redux Changing background colour of button in nested array using state
[英]Changing the background colour of a button (On/Off)
我已經查看了這個問題,但我沒有使用 angular。
到目前為止,這是我的代碼:
<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
不帶#
。 function 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>
給出以下 HTML
<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>Bx</button>
您將#Bx
作為 id 參數傳遞給您的切換 function。 這導致 js 調用:
document.getElementById("#Bx");
但是getElementById
function 不需要#
前綴。 嘗試將您的 HTML 更改為
<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>Bx</button>
修復您當前的問題
您的按鈕中不需要#
。 這么多就夠了:
<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>
#
是一個 CSS 選擇器,用於選擇您的 HTML id
元素。 您可以通過以下方式在 CSS 中引用它們:
#Bx {
color: #AAAAAA;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.