首页 > 解决方案 > 使一个单选按钮选择第二个镜像单选按钮

问题描述

我想这应该很简单......无论如何我有两组镜像的单选按钮,比如设置 A 和设置 B

在集合 a 中,有按钮 1、2 和 3

在集合 b 中,还有按钮 1、2 和 3

我想要的行为是当我单击集合 a 中的按钮 1 时,它会自动检查集合 b 中的按钮 1。

2A 和 2B 以及 3A 和 3B 相同。

谁能解释如何做到这一点?这似乎是一个非常简单的功能,但显然不可能通过谷歌找到答案,而且似乎以前也没有人在这里问过这个问题......:/

我想用 HTML / Javascript 做。没有查询。

谢谢!

标签: javascripthtmlcss

解决方案


if(o[i].checked!=true)设置前检查o[i].checked=true以避免无限反馈。

function radioChanged(name, value) {
  var n=name=="a"?"b":"a";
  var o=document.getElementsByName(n);
  for(var i=0; i<o.length; i++)
    if(o[i].value==value)
      if(o[i].checked!=true)
        o[i].checked=true;
};
<input type="radio" name="a" value="1" id="A1"
  onchange="radioChanged(this.name, this.value)">
<label for="A1">A1</label></input>
<input type="radio" name="a" value="2" id="A2"
  onchange="radioChanged(this.name, this.value)">
<label for="A2">A2</label></input>
<input type="radio" name="a" value="3" id="A3"
  onchange="radioChanged(this.name, this.value)">
<label for="A3">A3</label></input>
<hr>
<input type="radio" name="b" value="1" id="B1"
  onchange="radioChanged(this.name, this.value)">
<label for="B1">B1</label></input>
<input type="radio" name="b" value="2" id="B2"
  onchange="radioChanged(this.name, this.value)">
<label for="B2">B2</label></input>
<input type="radio" name="b" value="3" id="B3"
  onchange="radioChanged(this.name, this.value)">
<label for="B3">B3</label></input>


推荐阅读