我刚刚做了一个快速简单的测试,我的用户可以通过勾选 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”的元素的背景颜色。
最佳答案
您遇到重复 ID 的问题:
Element.id
If the id value is not the empty string, it must be unique in a document
拥抱功能addEventListener
对于绑定(bind)事件,它更花哨,更清晰,用于测试,阅读代码等。
此方法使用 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>
关于javascript - 使用javascript单击按钮更改元素的背景颜色样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53903870/