简体   繁体   English

按钮使用javascript检查复选框

[英]button checking a checkbox using javascript

I am trying to make a button that will toggle between three colors: black, green, and red and will either check a certain box depending on the color. 我试图制作一个可以在三种颜色之间切换的按钮:黑色,绿色和红色,并且可以根据颜色选择某个复选框。 Right now I can make the color toggle but I can't make the check boxes check. 现在,我可以进行颜色切换,但是不能使复选框处于选中状态。 I would appreciate the help. 我会很感激的。 I am a beginner (obviously). 我是一个初学者(很明显)。

Button color green: check box 1 按钮颜色为绿色:复选框1

Button color red: check box 2 按钮颜色为红色:复选框2

Button color black: do not check either box 1 or 2 按钮颜色为黑色:请勿选中框1或2

The script looks like: 该脚本如下所示:

<script>
var colors = ["green", "red", "black"] 

function setColor(el) { 
el.colorIdx = el.colorIdx || 0; 
el.style.color = colors[el.colorIdx++ % colors.length]; 
}

</script>

The HTML looks like: HTML看起来像:

<html>
<button onclick="setColor(this)">This is my Button</button>
<input type="checkbox" name="box1" id="box1" />
<input type="checkbox" name="box2" id="box2" />  
</html>

Thanks! 谢谢!

I'd suggest: 我建议:

var colors = ["green", "red", "black"];

function setColor(el) {
    el.colorIdx = el.colorIdx || 0;
    el.style.color = colors[el.colorIdx++ % colors.length];
    document.getElementById('box1').checked = el.style.color == 'green';
    document.getElementById('box2').checked = el.style.color == 'red';
}

JS Fiddle demo . JS小提琴演示

Do it like this: 像这样做:

var index = el.colorIdx++ % colors.length;
if( index == 2 ) //2 is the index of color black
{
  document.getElementById("box1").checked = false; 
  document.getElementById("box2").checked = false; 
}
else if( index == 0 )
{
   document.getElementById("box1").checked = true;     
}
else
{
   document.getElementById("box2").checked = true;       
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM