我已经摸索这个问题一个小时了,我不明白为什么单选按钮中会出现这种奇怪的行为。以下是我的代码:
<label>Language
<input type="radio" id="de" value="de" onclick="switchRadioButtons(this);" >de
<input type="radio" id="en" value="en" onclick="switchRadioButtons(this);" >en
<input type="radio" id="other" value="other" onclick="switchRadioButtons(this);" >other
<input type="text" id="language" value="" /><br />
</label>
<script>
function switchRadioButtons(element) {
console.log(element.value);
</script>
因此,在我看来,每当我单击值或按钮本身时,单选按钮的值都应该写入控制台。这对于按钮本身来说是正确的,但是如果我单击按钮之外的标签/描述,它总是会打印“de”(第一项),无论我做了什么(我也尝试过“switchRadioButtons(document.getElementById( '其他'));”没有效果)。
任何人都可以向我解释为什么会发生这种情况并可能提供解决方案吗?
最佳答案
您的所有输入都位于同一个标签内!如果你点击它,它将触发第一个元素(“de”)。它不知道您想要触发其他事件之一。
您需要为每个元素设置一个单独的标签。
关于javascript - 单选按钮 : weird selection behaviour,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17838455/