簡體   English   中英

更改按鈕中的顏色onclick事件

[英]change color onclick event in button

我在代碼中遇到問題。 我想在單擊按鈕時更改按鈕的顏色。 您可以檢查下面給出的代碼。

<html>
    <head>
    </head>
    <body onload="func();">
        <br><br><div id="header"><h1 align="center">Online Aptitude-2k17</h1></div>
        <table align="center" width="100%">
            <tr id="t1">
                <td></td>
            </tr>
        </table>

        <script>
            function func() {
                for(var i=1;i<=30;i++) {
                    var x=document.getElementById("t1").innerHTML;
                    var p="<td><input type='button' value='"+i+"' onclick ='myFunction("+i+");'/></td>";
                    document.getElementById("t1").innerHTML=x+p;
                }
            }

            function myFunction(a,elem) {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (this.readyState == 4 && this.status == 200) { 
                        document.getElementById("ques").innerHTML = this.responseText;

                    }
                };
                xhttp.open("GET", "retrieveQuestion.php?question=" +a, true);
                xhttp.send();
            }
        </script>

        <div id="ques" style="text-align:center; padding:20px"></div>
        <table align="center" cellspacing="20px">
            <tr><td align="center"><input type="text" name="answer" /></td></tr>
            <tr><td align="center"><input type="button" value="Submit" /></td></tr>
        </table>
      </body>
</html>

在單行中包含30列的按鈕,當用戶單擊時我想要的是它必須更改的顏色,單擊后它的顏色是必須的。

誰能幫我解決這個問題。

使所有顏色排成陣列

$("button").click(function(){
    var color = clicked ? 'red' : 'blue';
    $(this).css('background-color', color);
    clicked = !clicked;
});

這是一些示例,您可以嘗試用自己的代碼實現

 function changeColor(e){ e.style.backgroundColor = "red"; } function populate() { for(var i=1;i<=30;i++) { var x=document.getElementById("holder").innerHTML; var p="<input style='background-color: #4CAF50' type='button' value='"+i+"'onclick='changeColor(this)'/>"; document.getElementById("holder").innerHTML+=p; } } populate() ; 
 <div class="container"> <table id="holder"></table> </div> 

暫無
暫無

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

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