簡體   English   中英

使用 JavaScript/jQuery 更改所選按鈕的背景顏色

[英]change background color of selected button with 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";
    }
    );

}

問題包含帶有 json 格式選項的問題。 所選按鈕的顏色沒有改變,我真的是 JavaScript 的新手,請有人幫忙。

只需使用 jQuery object $(this) , $(this).css('background-color','red'); 單擊時更改按鈕顏色。

或者通過document.getElementById("Your-button-id")獲取 id。

注意:請避免不匹配 jQuer 和 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' />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM