Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用JavaScript变量设置选中单选按钮_Javascript_Html - Fatal编程技术网

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

使用JavaScript变量设置选中单选按钮,javascript,html,Javascript,Html,有没有办法使用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> <

有没有办法使用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>

无标题文件
var shirtColor=“绿色”;
document.getElementById(shirtColor);
衬衫颜色:
红色
绿色
蓝色的


只需将其
checked
属性设置为
true

document.getElementById(shirtColor).checked = true;

这是小提琴:

看起来是这样的

btn = document.getElementById("itsID");
btn.checked = true;

您可以这样使用jquery

$("control_id").attr("checked",true);

确保在执行此jquery之前加载元素。。为了安全起见,您应该始终将脚本放在页面末尾的
标记之前

,这可能是因为您必须将shirtColor而不是itsID放在页面末尾,“itsID”用作example@user1822824-您必须等待元素可用。将
脚本
放在
正文
标记的底部,在这些元素已经在页面上之后。