[英]Change element's background-color style on button click with javascript
我剛剛做了一個快速簡單的測試,我的用戶可以通過選中html復選框來選擇特定問題的答案。 我想提供一個功能,供用戶單擊特定的按鈕以將正確答案的背景顏色樣式更改為綠色,以便用戶可以知道他是否正確回答了。
我已經嘗試了多個基於javascript的代碼,這些代碼可以在google的前幾頁中找到。
<style>
#ca {
background-color:white;
}
</style>
<b>My question:</b>
<l>
<li id="ca"><input type="checkbox"> Answer 1</li>
<li><input type="checkbox"> Answer 2</li>
<li><input type="checkbox"> Answer 3</li>
<li id="ca"><input type="checkbox"> Answer 4</li>
</l>
<button type="button"
onclick="document.getElementById('ca').style.background-color = 'green'">
Show me the correct answers.</button>
正確答案用元素ID“ ca”指定。
我想在單擊按鈕時更改ID為“ ca”的元素的背景顏色。
var chkbox = document.getElementsByClassName("chkbox"); var x = document.getElementById("mylist"); function onChangeListener() { for (var i = 0; i < chkbox.length; i++) { if (chkbox[i].checked) { x.getElementsByClassName("ca")[i].style.backgroundColor = "green"; } else{x.getElementsByClassName("ca")[i].style.backgroundColor = "";} } }
<!DOCTYPE html> <html> <head> <style> div { border: 1px solid black; margin: 5px; } </style> </head> <body> <b>My question:</b> <l id="mylist"> <li id="ca" class="ca"><input type="checkbox" class="chkbox"> Answer 1</li> <li id="ca" class="ca"><input type="checkbox" class="chkbox"> Answer 2</li> <li id="ca" class="ca"><input type="checkbox" class="chkbox"> Answer 3</li> <li id="ca" class="ca"><input type="checkbox" class="chkbox"> Answer 4</li> </l> <button onclick="onChangeListener()"> Show me the correct answers.</button> </body> </html>
您的ID重復存在問題:
Element.id
如果id值不是空字符串,則它在文檔中必須是唯一的
擁抱addEventListener
函數來綁定事件,它看起來不錯,而且對於測試,閱讀代碼等更為清晰。
此方法使用樣式cans
,當單擊按鈕時會添加綠色背景。
document.getElementById('myButton').addEventListener('click', function() { Array.from(document.querySelectorAll('.ca')).forEach(function(e) { e.classList.add('cans'); }); });
.cans { background-color: green; }
<b>My question:</b> <l> <li class="ca"><input type="checkbox"> Answer 1</li> <li><input type="checkbox"> Answer 2</li> <li><input type="checkbox"> Answer 3</li> <li class="ca"><input type="checkbox"> Answer 4</li> </l> <button id='myButton' type="button"> Show me the correct answers.</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.