单击时切换按钮颜色

VIJ*_*IJU 1 html javascript jquery

JavaScript点击一次,我写了一个将按钮的颜色改为绿色,当我再次点击按钮时,它的颜色应该变回橙色.按钮的默认颜色为橙色.我已经给出了rgb颜色的值.但是,当我点击按钮时,它的颜色从橙色变为绿色,当我再次点击它时,它的颜色保持绿色不会变回橙色.请帮我解决这个问题.

<script>
function colorchange(id)
{

  var background = document.getElementById(id).style.background;

  if(background = "rgb(255,145,0)")
  {
  document.getElementById(id).style.background = "rgb(26,255,0)";
  }
  if(background == "rgb(26,255,0)")
  {
    document.getElementById(id).style.background = "rgb(255,145,0)";
  }

}
</script>
Run Code Online (Sandbox Code Playgroud)

这是输入按钮的HTML代码

<input type="button" name="Ignore Select" value="Ignore Select" id="select" onclick="colorchange('select')" style="background:rgb(255,145,0);"/>
<input type="button" name="Ignore Delete" value="Ignore Delete" id="select1" onclick="colorchange('select1');" style="background:rgb(255,145,0);"/>
<input type="button" name="Ignore Insert" value="Ignore Insert" id="select2" onclick="colorchange('select2');" style="background:rgb(255,145,0);"/>
<input type="button" name="Ignore Update" value="Ignore Update" id="select3" onclick="colorchange('select3');" style="background:rgb(255,145,0);"/>
<input type="button" name="Ignore Sleep" value="Ignore Sleep" id="select4" onclick="colorchange('select4');" style="background:rgb(255,145,0);"/>
Run Code Online (Sandbox Code Playgroud)

Aru*_*hny 9

它应该是 if(background == "rgb(255,145,0)")

使用比较运算符==而不是赋值=

function colorchange(id) {

    var background = document.getElementById(id).style.backgroundColor;
    if (background == "rgb(255, 145, 0)") {
        document.getElementById(id).style.background = "rgb(26,255,0)";
    } else {
        document.getElementById(id).style.background = "rgb(255,145,0)";
    }

}
Run Code Online (Sandbox Code Playgroud)

演示:小提琴


因为使用了jQuery标签

<input type="button" name="Ignore Select" value="Ignore Select" id="select" class="select" />
<input type="button" name="Ignore Delete" value="Ignore Delete" id="select1" class="select" />
<input type="button" name="Ignore Insert" value="Ignore Insert" id="select2" class="select" />
<input type="button" name="Ignore Update" value="Ignore Update" id="select3" class="select" />
<input type="button" name="Ignore Sleep" value="Ignore Sleep" id="select4" class="select" />
Run Code Online (Sandbox Code Playgroud)

然后

.select {
    background:rgb(255,145,0);
}
.select.highlight {
    background:rgb(26, 255, 0);
}
Run Code Online (Sandbox Code Playgroud)

jQuery(function ($) {
    $('.select').click(function () {
        $(this).toggleClass('highlight')
    })
})
Run Code Online (Sandbox Code Playgroud)

演示:小提琴