使用JavaScript变量设置选中的单选按钮

use*_*824 10 html javascript

有没有办法使用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>
Run Code Online (Sandbox Code Playgroud)

Jos*_*ber 25

只需将其checked属性设置为true:

document.getElementById(shirtColor).checked = true;
Run Code Online (Sandbox Code Playgroud)

这是小提琴:http://jsfiddle.net/akkSY/

  • @ user1822824 - 您必须等待元素可用.将``script`放在`body`标签的底部,这些元素已经在页面上. (7认同)