使用 JavaScript 变量设置选中的单选按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14612850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Checked Radio Button Using a JavaScript Variable
提问by user1822824
Is there a way to set the checked radio button using a JavaScript variable? I was hoping I could get the radio button by ID and update the checked radio.
有没有办法使用 JavaScript 变量设置选中的单选按钮?我希望我可以通过 ID 获取单选按钮并更新选中的收音机。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script>
var shirtColor = "green";
document.getElementById(shirtColor);
</script>
</head>
<body>
<p>Shirt Color:
<input type="radio" name="shirtColor" id="red" value="red" />
Red
<input type="radio" name="shirtColor" id="green" value="green" />
Green
<input type="radio" name="shirtColor" id="blue" value="blue" />
Blue</p>
</body>
</html>
回答by Joseph Silber
Just set its checkedproperty to true:
只需将其checked属性设置为true:
document.getElementById(shirtColor).checked = true;
Here's the fiddle: http://jsfiddle.net/akkSY/
这是小提琴:http: //jsfiddle.net/akkSY/
回答by igarcia
It would look like that
看起来像那样
btn = document.getElementById("itsID");
btn.checked = true;
回答by Vishal
you can use jquery in this way
你可以这样使用jquery
$("control_id").attr("checked",true);
be sure that element is loaded before this jquery is executed.. to be safe you should always put scripts in the end of the page before </body>tag
确保在执行此 jquery 之前加载元素.. 为安全起见,您应该始终将脚本放在页面末尾的</body>标签之前

