用JavaScript/jQuery改变选定按钮的背景颜色



我正在创建一个测验,并想更改用户选择的按钮的颜色。

var start = true;
if (start) {
begin(0);
}
function begin(id) {
// placing questions
const question = document.getElementById("question");
question.innerText = Questions[id].q;
// placing options
document.getElementById('op1').innerText = Questions[id].a[0].text;
document.getElementById('op2').innerText = Questions[id].a[1].text;
document.getElementById('op3').innerText = Questions[id].a[2].text;
document.getElementById('op4').innerText = Questions[id].a[3].text;
$(".btn").click(function () {
var selected = $(this).attr("id");
selected.style.backgroundColor="red";
}
);
}

Questions包含json格式的带有选项的问题。所选按钮的颜色没有改变,我真的是新的JavaScript,有人帮助请。

只需使用jQuery对象$(this),$(this).css('background-color','red');来改变点击时按钮的颜色。

或者通过document.getElementById("Your-button-id")获取id

注意:请避免jquery和JavaScript不匹配

例子:

$(".btn").click(function() {
$(this).css('background-color', 'red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="quiz" class='btn' id='btn' />

或:

$(".btn").click(function() {
let selected = document.getElementById("btn");
selected.style.backgroundColor = "red";
});
<!-- begin snippet: js hide: false console: true babel: false -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="quiz" class='btn' id='btn' />

最新更新