Hai*_* IT 0 html javascript radio-button
<input type="radio" value="0" name="type" checked="yes" />
<label>Type 0</label>
<input type="radio" value="1" name="type" />
<label>Type 1</label>
Run Code Online (Sandbox Code Playgroud)
和js:
var type = this.type.value;
alert(type);
Run Code Online (Sandbox Code Playgroud)
怎么解决?
JS代码在什么上下文中运行?如果this是有问题的单选按钮,则this.value返回该值.
如果您的问题是"我如何获得'类型'组中当前所选单选按钮的值?" 那么你可能需要做这样的事情:
function getCheckedRadioValue(radioGroupName) {
var rads = document.getElementsByName(radioGroupName),
i;
for (i=0; i < rads.length; i++)
if (rads[i].checked)
return rads[i].value;
return null; // or undefined, or your preferred default for none checked
}
var checkedValue = getCheckedRadioValue("type");
Run Code Online (Sandbox Code Playgroud)
(使用.querySelector()或更容易.querySelectorAll(),但并非所有浏览器都支持它们.)